I try to use 'redux toolkit' to create async function for my React Native app. below are my createAsyncThunk
function:
export const signin = createAsyncThunk(
"signin",
async (dispatch, getState) =>{
return await axios.post(localhost+'/api/user_auth/', {
email:'abc@example.com',
password:'password'
}).then(res=> console.log(res.data))
}
)
export const userSlice = createSlice({
name: 'user',
initialState: {
user:{},
status:null
},
extraReducers:{
[signin.pending]: (state, action)=>{
state.status = 'loading...'
},
[signin.fulfilled]: (state, action)=>{
state.status = 'success'
state.user = action.payload
},
[signin.rejected]: (state, action)=>{
state.status = 'failed'
},
},
reducers: {
},
})
when running the function everything seems to work, the console.log
inside the then()
will return the correct data. But when I log out the state.user
I will get:
{"status": "success", "user": {}}
- How should I return the response data?
- If I want only the specific part of the response data like
response.data
, how can I filter that to return toreducer
?
Update01 I just test this:
export const signin = createAsyncThunk(
"signin",
async (dispatch, getState) =>{
const res = await axios.post(localhost+'/api/user_auth/', {
email:'abc@example.com',
password:'password'
})
console.log( await res.data)
return await res.json()//<-- give status "failed"
}
)
And I when I logged state.user
, I will get:
{"status": "failed", "user": {}}
It seems like the toolkit is very particular on the await format.