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:
- if filter.location is null but filter.sensorType is not null then request = …farms?sensortype=abc&page=3
- if filter.location is not null but filter.sensorType is null then request = …farms?location=abc&page=3
- if both are null then requests = …farms?page=3
the result i got with my code was:
…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}`
);
>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}`
);