import React, { Component } from 'react';
import Axios from 'axios';
class App extends Component {
state = {
posts: []
}
componentDidMount() {
Axios.get('https://jsonplaceholder.typicode.com/posts?id=2&id=3')
.then(response => {
this.setState({ posts: response.data })
})
}
render() {
return(
<div>
{
this.state.posts.map ( (el,k) => <li> {el.title} </li> )
}
</div>
)}
}
export default App;
I am learning how to pass query params while calling APIs. The above code is working fine for me. Here i have passed id=2&id=3 as query params. I am using the following URL
Now, I am failing to pass title in the URL as params also. For e.g. the key-value pair of id=5 is "title": "nesciunt quas odio". So what is the proper way to pass it? Since the title has string value with the spaces in between.
My code should print the titles of id=2, id=3 and id=4; but for id=4 i shall pass the title itself in the params instead of id.
So, following command is rendering nothing on DOM
Axios.get('https://jsonplaceholder.typicode.com/posts?id=2&id=3&title=eum et est occaecati')
CodePudding user response:
trying to use this way
axios({
method: 'get',
params: {
"id" : 1,
"id" : 2,
"title" : "test"
},
url: 'https://jsonplaceholder.typicode.com',
responseType: 'json',
}).then((response) => {})
the axios handle the rest
CodePudding user response:
you can use the params option for axios
Axios.get('https://jsonplaceholder.typicode.com/posts', {
params : {
id : 1,
title : "ea molestias quasi exercitationem repellat qui ipsa sit aut"
}
})
CodePudding user response:
The way to syntax this is to split it with &
.
Example:
Axios.get('https://jsonplaceholder.typicode.com/posts?id=3&title=ea molestias quasi exercitationem repellat qui ipsa sit aut')
Once you input this you'll see that the browser replaces the spaces with
,
but that shouldn't matter.
CodePudding user response:
Kindly use 'encodeURIComponent' to encode strings containing special characters like space in the url
'https://jsonplaceholder.typicode.com/posts?title='
encodeURIComponent('eum et est occaecati')