I’m moving from Duck to redux toolkit.
Now I’ll try to explain this behavior, this thing: = await axios
always return the pending action. Removing the await
the api call "works", but return undefined
.
So what I’m missing here?
'movies/searchByTitle',
async (values, thunkAPI) => {
const API_KEY = '';
try {
let {movieTitle} = values;
let page = 1;
let movies = await axios
.get(
`//api.themoviedb.org/3/search/movie?query=${movieTitle}&api_key=${API_KEY}&include_adult=false&page=${page}`,
)
.then(response => {
console.log('results: ', response);
return response.data;
})
.catch(error => {
const message =
(error.response &&
error.response.data &&
error.response.data.message) ||
error.message ||
error.toString();
console.log(message);
thunkAPI.rejectWithValue(error);
});
return movies;
} catch (error) {
const message =
(error.response &&
error.response.data &&
error.response.data.message) ||
error.message ||
error.toString();
console.log(message);
return thunkAPI.rejectWithValue(message);
}
},
);
Edited: I did some changes, and now Im getting undefined
with fulfilled
action.
const API_KEY = '';
const fetchMoviesByTitle = async (title, page) => {
const url = `https://api.themoviedb.org/3/search/movie?query=${title}&api_key=${API_KEY}&include_adult=false&page=${page}`;
const {data} = axios.get(url);
return await data;
};
export const searchByTitle = createAsyncThunk(
'movies/searchByTitle',
async (values, thunkAPI) => {
let {movieTitle} = values;
let page = 1;
let data = await fetchMoviesByTitle(movieTitle, page)
.then(results => {
return results;
})
.catch(err => {
return thunkAPI.rejectWithValue(err.message);
});
console.log(data);
return data;
},
);
Thank you!!
2
Answers
you’re mixing
try / catch
withthen / catch
. Most of the time, you don’t do both of them at the same time. You can only choose one of them most of the time.Here’s an example with
try / catch
:or here’s an example with
then / catch
:In your updated code, you are still returning the
data
directly from the Axios response without awaiting it. You should use theawait
keyword when callingaxios.get(url)
to ensure that the asynchronous operation is completed and you have the response data before returning it. Here’s the corrected code:In this code:
We use
await
when callingaxios.get(url)
to ensure that the response is fully received before proceeding.We use a
try...catch
block to catch any errors that may occur during the Axios request. If an error occurs, we re-throw the error to be caught by thecreateAsyncThunk
function, which will result in a rejected action with the error message.With these changes, your
searchByTitle
thunk should now correctly return the response data when the request is successful or reject with an error message when an error occurs.