Strange behaviour of params.append with axios

Viewed 29
export const getCharactersAsync = createAsyncThunk('getCharactersAsync', async (data) => {
  const response = await axios.get('users', { params: { limit: data.limit } });
  return response.data;
});

this code block allows me to control limit attribute.

export const getCharactersAsync = createAsyncThunk('getCharactersAsync', async (data) => {
  const params = new FormData();
  // const params = new URLSearchParams();
  params.append('limit', data.limit);
  const response = await axios.get('users', params);
  console.log(response);
  return response.data;
});

However I cannot control limit with using params.append. I tried URLSearchParams instead of FormData but still cannot manipulate limit attribute of the response. Why they differ from each other?

1 Answers

docs

params are the URL parameters to be sent with the request. Must be a plain object or a URLSearchParams object

It can't be FormData

Solution

You wanted to use { params }, not params

export const getCharactersAsync = createAsyncThunk('getCharactersAsync', async (data) => {
  const params = new URLSearchParams();
  params.append('limit', data.limit);
  const response = await axios.get('users', { params });
  console.log(response);
  return response.data;
});
Related