I have a login component, a verification component and a userSlice
file which has createAsyncThunk
.
userSlice.js:
export const loginUser = createAsyncThunk(
'users/login',
async ({ email, password }, thunkAPI) => {
try {
const response = await fetch(
'my_url',
{
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
email,
password,
}),
}
);
let login_response = await response.json();
console.log('response login', login_response);
if (response.status === 200) {
console.log('success from here')
// localStorage.setItem('token', data.token);
return login_response;
} else {
return thunkAPI.rejectWithValue(data);
}
} catch (e) {
console.log('Error', e.response.data);
thunkAPI.rejectWithValue(e.response.data);
}
return login_response;
}
);
Here I get a response back when I post data. I have named it as login_response
.
I simply need to pass it to my verification component.
I searched for it online but I did not understand the solutions which were there.
In my verification component I have imported loginUser like so
import { loginUser } from '../features/user/userSlice';
I know that loginUser has returned login_response. Now how do I access login_response in the verification component ?
2
Answers
I guess you can access it using :
according to doc at https://redux-toolkit.js.org/api/createAsyncThunk :
createAsyncThunk returns a standard Redux thunk action creator. The thunk action creator function will have plain action creators for the pending, fulfilled, and rejected cases attached as nested fields.
now you can access it in your verification component
do not forger to export slice and add it to your store
and then in verification component:
console.log it to verify if you are getting right data.