Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

return empty string if condition isn't met

please i want to make the request filter option for location or/and sensorType return an empty string if any of them is null, i’m using select dropdown to change the values of filter.location and filter.sensorType

expected output:

  1. if filter.location is null but filter.sensorType is not null then request = …farms?sensortype=abc&page=3
  2. if filter.location is not null but filter.sensorType is null then request = …farms?location=abc&page=3
  3. if both are null then requests = …farms?page=3

the result i got with my code was:
…farms?location=abc&undefined&page=3

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const [filter, setFilter] = useState({
  sensorType: null,
  location: null,
});


// API REQUEST
const {
  data
} = await axios.get(
  `http://localhost:8080/api/farms?${
          filter.location && `location=${filter.location}`
        }${filter.sensorType && `&sensorType=${filter.sensorType}`}&page=${page}`
);

>Solution :

Just use the ternary conditional operator:

condition ? resultIfTruthy : resultIfFalsy
const [filter, setFilter] = useState({
  sensorType: null,
  location: null,
});


// API REQUEST
const {
  data
} = await axios.get(
  `http://localhost:8080/api/farms?${
          filter.location ? `location=${filter.location}` : ''
        }${filter.sensorType ? `&sensorType=${filter.sensorType : ''}`}&page=${page}`
);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading