skip to Main Content

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


  1. you’re mixing try / catch with then / 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:

      '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}`,
            )
            console.log('results: ', movies);
          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);
        }
      },
    );
    

    or here’s an example with then / catch:

    'movies/searchByTitle',
      async (values, thunkAPI) => {
        const API_KEY = '';
        return 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);
              return thunkAPI.rejectWithValue(error);
            });
      },
    );
    
    Login or Signup to reply.
  2. In your updated code, you are still returning the data directly from the Axios response without awaiting it. You should use the await keyword when calling axios.get(url) to ensure that the asynchronous operation is completed and you have the response data before returning it. Here’s the corrected code:

    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}`;
      try {
        const response = await axios.get(url);
        return response.data;
      } catch (error) {
        throw error; // Re-throw the error to be caught by the async thunk
      }
    };
    
    export const searchByTitle = createAsyncThunk(
      'movies/searchByTitle',
      async (values, thunkAPI) => {
        let { movieTitle } = values;
        let page = 1;
    
        try {
          let data = await fetchMoviesByTitle(movieTitle, page);
          console.log(data);
          return data;
        } catch (error) {
          return thunkAPI.rejectWithValue(error.message);
        }
      },
    );
    

    In this code:

    1. We use await when calling axios.get(url) to ensure that the response is fully received before proceeding.

    2. 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 the createAsyncThunk 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search