L
L
lexstile2022-02-08 12:36:30
React
lexstile, 2022-02-08 12:36:30

Is it possible not to send empty values ​​in a get request via axios?

You must not send empty get parameters (not only when they are equal to undefined, but also when they are equal to the empty string).
Apart from such a hack or a reduction to a check ( { q: search || undefined } ), nothing could be done.

const { data = [] } = await axios.get(API.TEST, {
      params: {
        ...(search ? { q: search } : {}),
        ...(dateStart ? { dateStart } : {}),
        ...(dateEnd ? { dateEnd } : {}),
      },
    });

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander, 2022-02-08
@Aleksandr-JS-Developer

You can try to automate the collection of parameters and checking them for emptiness.

const emptys = ['', undefined];

const noEmpty = (value, key) =>
  emptys.includes(value) ? {} : { [key]: value };

const params = [
  [search, 'q'],
  [dateStart, 'dateStart'],
  [dateEnd, 'dateEnd'],
].map((n) => noEmpty(n[0], n[1]));

const { data = [] } = await axios.get(API.TEST, {
  params: Object.assign({}, ...params),
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question