0

I have a react/typescript application made of client and server. The client asks the server for some data and proceeds to show it with React.

On the client side, when asking for data, I do:

export const createApiClient = (): ApiClient => {
    return {
        getTickets: () => 
            return axios.get(APIRootPath).then((res) => res.data);
        }
    }
}

On the server-side, sending data, I do:

app.get(APIPath, (req, res) => {  // @ts-ignore
  const page: number = req.query.page || 1;

  const paginatedData = tempData.slice((page - 1) * PAGE_SIZE, page * PAGE_SIZE);

  res.send(paginatedData);
});

Now, I was asked to do the following:

  1. Add a query param ?search= to the /tickets API call and implement it on the server-side.
  2. Connect your client-side search bar to that API call

I understand that the server, before sending the data back, should filter it by some string 'x', which gets inputted on the search bar.

What I don't understand from the question (and since I'm not familiar with web development at all), is how the server should receive this string.

Assuming that I was already able to connect the search bar in a way that shows the input on the URL. How would I send this parameter to the server? Do I even have to send it? Or should I be able from the server to extract the parameter myself?

Thank you for the help

Iam Spano
  • 31
  • 6
  • The parameter should be appended to the url before making the request (with axios). So in the handler of the button that starts the search you have to make trigger request with the search parameter appended to the url. The parameter will then be available in `req.query.search` on the server. Probably your `getTickets` method should accept a parameter `search` that it appends as a query parameter to the url if present. – trixn Mar 05 '21 at 14:04

1 Answers1

0

You do not need to show the query URL on your browser bar. To me it is not clear if you are supposed to implement a dynamic search where you ask the server new results as the user inputs characters or if you need the user to input all the search string and then ask your API for a response.

Anyway the only thing that changes is the trigger event: in the first case, assuming you are using an input tag, you need to use the onChange properties to invoke your function fromm your jsx like that:

<input type="text" [...] onChange={yourFunction} />

You may also need to change your API call to pass your query params into something like:

return axios.get(APIRootPath, { params: { param1: 42, param2: "some string").then((res) => res.data);

In the second hypotesis, you can have a button that uses an onClick event to start the same procedure

Mellgood
  • 195
  • 2
  • 12