0

halo guy, i'm creating a project using redux react & i'm getting this err, which i'm not familiar with below is my code & err

store

const reducer = {
    auth: authReducer,
    msg: msgReducer,
    data: dataReducer
}


const store = configureStore({
     reducer: reducer,
     devTools: true,
     middleware: [thunk]
})

slice file

export const fetchUserArticle =createAsyncThunk(
    'article/get-article-user',
    async(id, thunkAPI)=>{
        try{
            const response = await dataService.getUserArticles(id)
            thunkAPI.dispatch(setMessage(response.msg))
            
            return response
        }
        catch(err){
            const message = (
                err.message 
            ) || err.response ||
            err.toString()
            thunkAPI.dispatch(setMessage(message))
            return thunkAPI.rejectWithValue()
        }
    }
)

#other page

   useEffect(()=>{
        dispatch(getUserArticle())
    },)


    const getUserArticle =() =>{
        dispatch(fetchUserArticle(user._id))
            .unwrap()
            .then((res) =>{
                article = res.data
                setArticle(articles, res.data)
              }
        )
    }

err msg

react-dom.development.js:22839 Uncaught Error: Actions must be plain objects. Use custom middleware for async actions.

please can anyone help or have any idea how i can fix this err

Tosin Ayoola
  • 77
  • 1
  • 9

1 Answers1

0

The error is because you are calling dispatch with a function you created yourself in the useEffect().

The createAsyncThunk creates a plain object with information to process the async request.

So you should be using dispatch(fetchUserArticle(user._id)) there instead, as dispatch will know how to deal with the result of that function.

As you are not calling that dispatch with a plain object (action) you are getting the error.

MarkSkayff
  • 1,334
  • 9
  • 14
  • thanks, it worked, but when i use useState to assign the api reponse eg setRespne(resp.data) to a response variable, it doesnt work, the variable return blank u have any idea on why that doesnt work ? – Tosin Ayoola Jan 27 '23 at 22:17
  • Ok, two things. Check you don't have a typo. 2nd, I see you are passing two arguments to the state setter function. This state setter funciona only accept a single argument, which is the final value for the state variable (can be an object) – MarkSkayff Jan 29 '23 at 01:29