How to call react-redux slice method inside same slice's another method?

I’m using react-redux in my react app. I need a reducer function to set search query and another reducer function to fetch data according to that query. Here is my slice.

export const movieSlice = createSlice({
  name: 'movieSlice',
  initialState: {
    query: '',
    movie_results: [],
  },
  reducers: {
    setQuery: (state, action) => {
      state.query = action.payload
      console.log('state.query',state.query)
      setMovieResults()
    },
    setMovieResults: async (state)=>{
        const url = 'https:...'
        if(state.query !== ''){
            const res = await axios.get(url)
            console.log(res)
        }
    },
}
})

I need to call ‘setMovieResults’ in ‘setQuery’ reducer function. How do i do this?

>Solution :

The functions passed to the reducers parameter can be accessed through the caseReducers return field.

https://redux-toolkit.js.org/api/createSlice#return-value

   setQuery: (state, action) => {
      state.query = action.payload
      console.log('state.query',state.query)
      movieSlice.caseReducers.setMovieResults() /* New - you have to call it with a valid parameter. */
    },

Leave a Reply