Reputation: 31
i am getting the json from api but it is not converting to array previously i got the values but from this code i am not getting the value
this is my code:
componentWillMount() {
let initialFilename;
fetch('http://localhost/Generator/FetchfileDetails.php')
.then(response=>{
return response.json();
}).then(data=>{
alert(data.filename);
});
}
the key value in my json is filename is to be stored in array how to do???
Upvotes: 0
Views: 2453
Reputation: 20765
First thing keep in mind don't use componentWillMount() method to fetch the data.
Ref: https://reactjs.org/docs/faq-ajax.html#how-can-i-make-an-ajax-call
Use following,
componentDidMount(){
fetch("http://localhost/Generator/FetchfileDetails.php")
.then(res=> res.json())
.then(data=>{ //here you can set data to state })
}
Upvotes: 1
Reputation: 77
i recommended u used package axios for GET data,it's so easily to use..
axios.get('API').then(response=>{console.log(response)})
You can insert this code in the componentDidMount function
if u want to see the full documentation axios,This Link
Upvotes: 1
Reputation: 125
You can try instead of response.json() you can do:
fetch("http://localhost/Generator/FetchfileDetails.php") .then(response=>{ return JSON.parse(response) }).then(data=>{ alert(data);})
Also, if you say the response is supposed to be an array, you can't use data.filename , you have to do data['filename'] , data.filename is for object responses
Upvotes: 0