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();
Related
I'm getting some data from server and have set-up this service on client to request them accordingly:
const serviceSyncFollowedArtists = async userId => {
if (!userId) return
const { data } = await axios.get(`${httpLink}/sync`, {
params: {
accessToken,
userId,
},
})
return data
}
service is called within context:
const syncFollowedArtists = async () => {
await spotifyService
.serviceSyncFollowedArtists(user.userId)
.then(res => {
if (res.length === 0) return
dispatch({
type: 'SYNC',
data: res,
})
})
.catch(err => {
console.log(err)
})
}
It works fine as I want it to, however, before, I have set up the service to request data using promises:
const serviceSyncFollowedArtists = async userId => {
if (!userId) return
await axios
.get(`${httpLink}/sync`, {
params: {
accessToken,
userId,
},
})
.then(res => {
return res.data
})
.catch(err => {
console.log(err.message)
})
}
Even though I manage to obtain the data from server inside the service, when it's returned to the function in context, it's empty, undefined. Is threre any reason for this?
You are getting undefined because you are not returning anything from the function in the case of promises, unlike you are doing it in the first case
So just add a return keyword
const serviceSyncFollowedArtists = async userId => {
if (!userId) return
return await axios
.get(`${httpLink}/sync`, {
params: {
accessToken,
userId,
},
})
.then(res => {
return res.data
})
.catch(err => {
console.log(err.message)
})
}
I made a function to get request. It look like this
export const toggleCompleted = (id) => {
axiosMethod.get('api/taks/toggle/' + id)
.then(res => {
console.log(res.data)
return res.data;
}).catch(error => {
return error;
})
return 'Test';
}
I want to get this request and if PHP return true, run dispatch. So I made this code
const markAsCompleted = (id) => {
console.log(toggleCompleted(id));
if (toggleCompleted(id) == 1){
toggleMarkAsCompleted(id);
}
}
toggleCompleted is a my request which is show before
toggleMarkAsCompletedis my dispatch.
If toggleCompleted return 1 I want to run my dispatch. It's simple? Interested is that this code
console.log(toggleCompleted(id));
return Test while my request 1 or 0 (from .then()). Why?
Add return in the toggleCompleted and use async/await to get return data
export const toggleCompleted = (id) => {
return axiosMethod
.get("api/taks/toggle/" + id)
.then((res) => {
console.log(res.data);
return res.data;
})
.catch((error) => {
return error;
});
};
const markAsCompleted = async (id) => {
const res = await toggleCompleted(id);
if (res == 1) {
toggleMarkAsCompleted(id);
}
};
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
I have a function that fetches data from the url and is supposed to return it:
const fetchTableData = () => {
fetch('https://api.myjson.com/bins/15psn9')
.then(result => result.json())
.then(data => {
return data;
})
}
export default fetchTableData;
The problem is that when i import this function and try to use it, it always returns undefined.
When i console log the data inside the function itself, you can see it is available. The function just doesn't work when i try to import it.
What is the problem here? Why does it work that way?
Try this =) You have to return something from the fetchTableData function also.
const fetchTableData = () => {
const fetchedData = fetch('https://api.myjson.com/bins/15psn9')
.then(result => result.json())
.then(data => {
return data;
})
return fetchedData;
}
export default fetchTableData;
Or you can just return it like this:
const fetchTableData = () => {
return fetch('https://api.myjson.com/bins/15psn9')
.then(result => result.json())
.then(data => {
return data;
})
}
export default fetchTableData;
In your code you were not returning from the fetchTableData function. Only from the the second then() callback. When a function has no return value, undefined will be returned.
Try this instead:
const fetchTableData = () => {
const myResponse = fetch('https://api.myjson.com/bins/15psn9')
.then(result => result.json())
.then(data => {
return data;
})
return myResponse;
}
export default fetchTableData;
What now happens is the following:
The response return by the second then() function is returning the data.
We are saving this data in a variable, named myResponse.
We are now returning this value from the function fetchTableData.
You need to either store data in a global variable or assign any variable to fetch to get return data.
//First way
fetch('https://api.myjson.com/bins/15psn9')
.then(result => result.json())
.then(data => {
console.log("data",data);
});
//Second way
let binData = null;
fetch('https://api.myjson.com/bins/15psn9')
.then(result => result.json())
.then(data => {
binData = data;
console.log("binData", binData);
});
Here is the working example.
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)));
}
}