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 a select dropdown to change the values of filter.location and filter.sensorType
Expected output:
request = ...farms?sensortype=abc&page=3request = ...farms?location=abc&page=3requests = ...farms?page=3My current result:
...farms?location=abc&undefined&page=3
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}`
);
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}`
);