How can i get json in axios with react native? - javascript

I'm trying to get json in axios
but if i use my code this error and warning occured
How can i get response.json ??
response.json is not a function
this is my code
// url="https://yts.lt/api/v2/list_movies.json?sort_by=like_count&order_by=desc&limit=5"
url is props
useEffect(() => {
axios
.get(url)
.then((response) => response.json())
.then((json) => {
console.log('json', json);
setData(json.data.movies);
})
.catch((error) => {
console.log(error);
});
}, []);

The response object from axios stores its data in response.data.
useEffect(() => {
axios
.get(url)
.then((response) => {
const json = response.data;
console.log('json', json);
setData(json.data.movies);
})
.catch((error) => {
console.log(error);
});
}, []);

Use this:
useEffect(() => {
axios
.get(url)
.then((response) => response.data)
.then((json) => {
console.log('json', json);
setData(json.data.movies);
})
.catch((error) => {
console.log(error);
});
}, []);

Related

Why is my setStateAction not updating with json response data?

I am trying to fetch user data using the GitHub API, but when I make a request using fetch() the request is not sent until after the return(). The response data will only show after the page loads, but I need it before render to use as HTML parameters. I know it has something to do with JSON requests being asynchronous, but I'm not sure how to change the code to set the data properly.
const user = params.get("user");
const [userData, setUserData] = useState(null);
const [reqLimit, setReqLimit] = useState(null);
const getUserData = () => {
fetch(`https://api.github.com/users/${user}`)
.then(response => {response.json();})
.then(json => console.log(json))//'undefined'
.then(json => setUserData(json))
.catch(error => {
console.error('Error:', error);
});
};
useMemo(() => {
fetch(`https://api.github.com/rate_limit`)
.then(response => response.json())
.then(json => {
setReqLimit(json.resources.core);
if (json.resources.core.remaining < 1) {
console.error('Error:', 40
}
});
getUserData();
}, [userData]);
return (
<main>
//userData = null; (Why?)
</main>
)
fetch(`https://api.github.com/users/${user}`)
.then(response => response.json();) // return json
//.then(json => console.log(json))//'undefined' remove this from here
.then(json => setUserData(json))
.catch(error => {
console.error('Error:', error);
});

Why is my JSON response returning undefined?

I'm trying to make a fetch request for COVID data in my React Native app but each time I try to inspect the response, the console outputs undefined for the json variable:
const [isLoading, setLoading] = useState(true);
const [data, setData] = useState({});
useEffect(() => {
fetch("https://api.covid19api.com/summary")
.then((response) => {
response.json();
})
.then((json) => {
console.log("json.. " + json);
setData(json);
})
.catch((error) => console.error(error))
.finally(() => setLoading(false));
}, []);
In the first .then(), you are not returning anything, so undefined is returned implicitly.
You should return the reponse.json():
.then((response) => {
return response.json();
})
Or shorter:
.then((response) => response.json())

What would this code look like if instead of "async/await" use "then and catch"?

There is such a method in a React application:
fetchData = async () => {
try {
const response = await fetch(`https://........`);
const data = (await response.json()).group;
this.setState({
data: data,
car: Object.keys(data)[0]
},this.filter);
} catch(err) {
console.log("404 Not Found");
}
};
How to write this part without async / await syntax, and using then and catch?
Just like this!
fetchData = () => {
fetch("YOUR_URL")
.then(response => response.json())
.then(json => json.group)
.then(data => {
this.setState({
data,
car: Object.keys(data)[0]
},this.filter);
})
.catch(err => {
console.log("404 Not Found");
});
}
It's simply-
fetchData = () => {
fetch(url)
.then(res => res.json())
.then(data => {
this.setState({data: data.group, car: Object.keys(data.group)[0]})
})
.catch(err => console.log(err));
};
If fetch returns a Promise you can:
fetchData = () => {
fetch(url)
.then(res => ... )
.catch(err => ...)
};
fetchData = () => {
return fetch(`https://........`)
.then(response => {
const data = response.json().group;
this.setState({
data: data,
car: Object.keys(data)[0]
},this.filter);
}).catch(err => {
console.log("404 Not Found");
});
};
response.json() won't return a Promise so you don't need await

The second and consequent then are not working

Only the first then is working. Every subsequent then is not working.
export const usersFetchData = (url) => {
return (dispatch) => {
dispatch(userIsLoading(true));
axios
.get(url)
.then(res => {
if(!res.ok){
throw Error(res.statusText)
}
dispatch(userIsLoading(false));
console.log(res.data);
return res;
})
.then(res => res.json())
.then(users => {
console.log(users);
dispatch(usersFetchDataSuccess(users))})
.catch(() => dispatch(userHasErrored(true)));
}
}
axios converts it into JSON for you, you don't have to do it yourself like you do in fetch
export const usersFetchData = (url) => {
return (dispatch) => {
dispatch(userIsLoading(true));
axios
.get(url)
.then(res => {
if(!res.ok){
throw Error(res.statusText)
}
dispatch(userIsLoading(false));
console.log(res.data);
return res.data; // returning the json respone
})
//.then(res => res.json()) // removed this, you don't need it
.then(users => {
console.log(users);
dispatch(usersFetchDataSuccess(users))
})
.catch(() => dispatch(userHasErrored(true)));
}
}

Can I pass dynamic values to ES6's Template Literals?

getSelectedCityId() {
let citiName
citiId;
axiosInstance
.get("/api/cities")
.then(response => {
if (response.status === 200 && response.data) {
citiName = this.state.city;
citiId = this.state.city.city_id;
}
})
.catch(error => {});
let url = `/api/${citiName}/${citiId}/schools/`;
axiosInstance
.get(url)
.then(response => {
})
.catch(error => {
console.log(error);
});
}
When I hit that API call,the url shows :
localhost:9000/api/undefined/undefined/schools/
I'm trying to pass the data I will get from the 1st API call as a parameter to the second API.My point is,why the template literal is throwing undefined ? Are we not allowed to pass dynamic data through template literals ?
getSelectedCityId() {
let citiName
citiId;
axiosInstance
.get("/api/cities")
.then(response => {
if (response.status === 200 && response.data) {
citiName = this.state.city;
citiId = this.state.city.city_id;
this.getSelectedCityIdStepTwo(`/api/${citiName}/${citiId}/schools/`);
}
})
.catch(error => {});
}
getSelectedCityIdStepTwo(url) {
axiosInstance
.get(url)
.then(response => {
})
.catch(error => {
console.log(error);
});
}
This will ensure the second AXIOS call isn't made until the first one is completed and there is a valid URL to pass.
Since getting /api/cities data is async operation, you need to wait for the result. Just for proof of concept:
getSelectedCityId()
{
let citiName
citiId;
axiosInstance
.get("/api/cities")
.then(response => {
if (response.status === 200 && response.data) {
citiName = this.state.city;
citiId = this.state.city.city_id;
return `/api/${citiName}/${citiId}/schools/`;
}
return null;
})
.then(url => {
if(url) { // the data from previous then
axiosInstance.get(url) //.then().catch()
}
});
}

Categories