🦊 Search and File Uploads 🦊
Posted on Sep 26th, 2022
🗓️ Today’s Topics
- Implementing search in your application 🔍
- Image & file uploads: forms and requests
Example Search Request with Query Params
Remember the iTunes API? To get search results, you needed to include query params that specified the search fields and terms you wanted to use.
Here’s how you might make a request that uses query params using axios. (Note: this example depends on searchTerm
and token
being defined in your code.)
axios.get('https://drf-library-api.herokuapp.com/api/books',
{
params: {search: searchTerm},
headers: {Authorization: `Token ${token}` }
}
)
A note on search in React
You could also perform a search without making an AJAX request, by filtering data that you already have in React. Here are a couple of examples of how you could do that.
Example Request to Upload a File
This is an update to an existing record; notice that we are using the PATCH verb. In this case you are including the file itself as the body of the request; notice that the file is in the second position as an argument to axios.patch()
as the body of the request. We are also setting specific headers required by the server to handle the binary file attachment, in addition to the Authorization header.
axios.patch(url, file, {
headers: {
Authorization: 'Token ' + token,
'Content-Type': file.type,
'Content-Disposition': `attachment; filename=${file.name}`
}
}).then(res => console.log(res.data))
NOTE: If you Google how to include a file attachment in an AJAX request, you’ll see a lot of references to using the FormData object. If you want to do it this way, please discuss with your back end devs, as they will need to make sure that they can parse MultiPart form content.
The above method does not use the FormData object. It’s a little simpler in that it sends just the file and no additional data. You’ll need a way to access the file that is being uploaded by the user.
See the resources below for more information about using a file input element and accessing a selected file. The useRef()
hook will be helpful to get the files from the input element after a user has selected a file using the form.