Search code examples
reactjsreact-reduxreact-hooksuse-stateredux-toolkit

Troubles to pass an value through Redux Toolkit


i'm currently working on a project for my portfolio The project is a basic, website using TheMovieDb APP on React

I'm using redux toolkit to provide DATAS through all my components this first hooks is working well when i call it in the home components

export const GetActualFilms = async () => {
const dispatch = useDispatch();
api.get(`trending/movie/week?${KEY}&language=fr`)
//SUCCESS
.then((res) => dispatch(setActualFilmsData(res.data.results)))
//ERROR
.catch((error) => console.log(error, "une erreur s'est produite"));
return;};

but this other One is crashing my app with an hooks error: Error

export const GetFilmsDetail = async () => {
    const moviesSearched = useSelector(storedSearchedFilmsData);
    console.log("OK", moviesSearched.searchResults);
    const dispatch = useDispatch();
    api.get(`search/movie?${KEY}&query=${moviesSearched}&language=fr`)
        //SUCCESS
        .then((res) => console.log(res), dispatch(getSearchedFilmsData(res.data.results)))
        //ERROR
        .catch((error) => console.log(error, "une erreur s'est produite"));
    return;};

theses DATAS are used for a search input and passed by a Dispatch

export const NavBar = () => {
const [searchedMovies, setSearchedMovies] = useState([]);
const dispatch = useDispatch();

const handleSubmit = (e) => {
    e.preventDefault(searchedMovies);
    const adjustSearchedMovies = searchedMovies.toString().replace(/ /g, "+");
    dispatch(storedSearchedFilmsData(adjustSearchedMovies));
    GetFilmsDetail();
};

Am i doing something wrong ? Thank you for your reading


Solution

  • In React, you are not allowed to use something like useDispatch or useSelector outside of a React component body - also not in event handlers etc.

    I'd highly encourage you to write a thunk for this logic - maybe give a read to chapter 5 of the official Redux tutorial (while chapters 7 and 8 might also be of interest to you here).

    Generally, you would write a thunk here and instead of GetFilmsDetail() you would call dispatch(getFilmsDetailThunk()).

    export const getFilmsDetailThunk = async () => (dispatch, getState) => {
        const moviesSearched = storedSearchedFilmsData(getState());
        console.log("OK", moviesSearched.searchResults);
        try {
          const res = await api.get(`search/movie?${KEY}&query=${moviesSearched}&language=fr`)
          console.log(res)
          dispatch(getSearchedFilmsData(res.data.results))
        } catch (error) {
          console.log(error, "une erreur s'est produite")
        }
    }
    

    (Also, please use async await intead of then and catch, that will make your code a lot more readable!)