The second and consequent then are not working - javascript

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)));
}
}

Related

How can i get json in axios with react native?

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);
});
}, []);

Returning value from a function in react

When I'm trying to return my res.data from my function and then console.log it I get undefined but if I console.log it from inside the function I get the normal result
const getDefaultState = () => {
axios
.get("http://localhost:5000/urls/todos")
.then((res) => {
if (res.data) {
console.log(res.data);
return res.data;
}
})
.catch((err) => console.log(err));
};
console.log(getDefaultState());
so I get first
(3) [{…}, {…}, {…}]
(the normal value)
but then from outside I get
undefined
You need to return the call as well:
const getDefaultState = () => {
return axios.get("http://localhost:5000/urls/todos")
.then((res) => {
if (res.data) {
console.log(res.data);
return res.data;
}
}).catch((err) => console.log(err));
}
You should return the promise instead.
const getDefaultState = () =>
axios
.get("http://localhost:5000/urls/todos")
.then((res) => {
if (res.data) {
console.log(res.data);
return res.data;
}
})
.catch((err) => console.log(err));
That way you can listen to the result outside the function:
getDefaultState().then(/* do stuff */);
// or
const res = await getDefaultState();

How to call multiple fetch APIs

I have to make a fetch call at a url and after getting its response I want to use those results to call another fetch. I have following code:-
async function getDate(request) {
let data;
console.log('handle request called')
await fetch('<first-url>')
.then(res => {
let urls = res.json()
console.log('urls are ', urls)
return urls.data
})
.then((urls) => {
let url = urls[0]
console.log('url is ', url)
return fetch(url)
})
.then((res) => {
data = res.body
})
.catch(() => {
console.log("something went wrong")
})
return new Response(data, {
headers: { 'content-type': 'text/html' },
})
}
I followed the above method after following this tutorial. However it does not seem to work and I am getting urls are {Promise:[Pending]}.
Here issue with return res.json(). res.json() is promisable object, so u have to resolve it to get data.
For your example:
const fetch = require("node-fetch");
async function getDate() {
let data;
console.log("handle request called");
return await fetch('<first-url>')
.then((res) => res.json())
.then((urls) => {
console.log("urls are ", urls);
if (urls.length)
return Promise.all(urls.map((url) => fetch(url).then((x) => x.json())));
return [];
})
.then((responses) => {
console.log("urls are ", responses);
return responses;
});
}
getDate().then(console.log);
Sample:
async function getDate() {
let data;
console.log("handle request called");
return await fetch("https://api.covid19api.com/countries")
.then((res) => res.json())
.then((urls) => {
console.log("urls are ", urls);
return urls;
});
}
getDate().then(console.log);

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

Promise pattern falling back multiple fetches

I'm using fetch promises to fall back through 3 API calls until one succeeds. I'm not sure what the best pattern is for that. I'd like to use something like this, where promise rejection is handled by the next catch and fetches the next URL.
The issue is that successfully resolved data is picked up by .then(res => res.json())
fetch(url1)
.then(res => res.json())
.then(data => {
if (data.status !== 'OK') {
return Promise.reject()
}
return Promise.resolve(data)
})
.then(null, () => {
return fetch(url2)
})
.then(res => res.json())
.then(data => {
if (!data.success) {
return Promise.reject()
}
return Promise.resolve(data)
})
.then(null, () => {
return fetch(url3)
})
.then(res => res.json())
.then(data => {
if (data.error) {
return Promise.reject()
}
return Promise.resolve(data)
})
The success checks are different for each function, so I can't easily use a loop that breaks on success.
Just group the optional API call and processing in the catch function:
fetch(url1)
.then(res => res.json())
.then(data => {
if (data.status !== 'OK') {
return Promise.reject()
}
return Promise.resolve(data)
}).catch(function() {
return fetch(url2)
.then(res => res.json())
.then(data => {
if (!data.success) {
return Promise.reject()
}
return Promise.resolve(data)
});
}).catch(function() {
return fetch(url3)
.then(res => res.json())
.then(data => {
if (data.error) {
return Promise.reject()
}
return Promise.resolve(data)
})
});
You could use Promise.all or Promise.race, and wrap the checks on functions.

Categories