'How to I dispatch a state value to an const variable in Redux-toolkit?
I am trying get an error to show in my component which is being dispatched from my actions and assigned to my errorAlert constent, however it always comes back as null even when there is content in my state as per console.log. I have shared the console log results below.
Is there an issue when assigning a redux state variable to a const?
slice.js
const auth = createSlice({
name: "auth",
initialState: verifiedResult: {},
reducers: {
verifySuccess(state, { payload }) {
state.verifiedResult = payload;
state.isLoading = false;
state.error = null;
}
}
action.js
...
if (result.state === "pending") {
await new Promise((resolve) => setTimeout(resolve, 10000));
} else if (result.state === "failed") {
dispatch(verifySuccess(result));
break;
component.js
....
const errorAlert =
auth.verifiedResult.cel_number === false
? "The number associated with your account is not a valid."
: auth.verifiedResult.prepaid_number === false
? "Mobile number is not Prepaid or is not active."
: auth.verifiedResult.has_recharged === false
? "Mobile number must be recharged in the past 30 days"
: null;
return (
<>
{errorAlert && <div>{errorAlert}</div>}
</>
)}
console.log
::auth.verifiedResult::
{
state: "failed"
cel_number: 'XXX XXX XXX'
prepaid_number: false
recharged: false
}
:::errorAlert::: null
Solution 1:[1]
It shows Mobile number is not Prepaid or is not active. in my case. Make sure your auth.verifiedResult is correctly written(you don't use comma after every object property).
const auth = {};
auth.verifiedResult = {
state: 'failed',
cel_number: 'XXX XXX XXX',
prepaid_number: false,
recharged: false,
};
const errorAlert =
auth.verifiedResult.cel_number === false
? 'The number associated with your account is not a valid.'
: auth.verifiedResult.prepaid_number === false
? 'Mobile number is not Prepaid or is not active.'
: auth.verifiedResult.has_recharged === false
? 'Mobile number must be recharged in the past 30 days'
: null;
console.log(errorAlert); // Mobile number is not Prepaid or is not active.
Solution 2:[2]
Did you mean
if (result.state === "pending")?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Robin |
| Solution 2 | Guillaume Brunerie |

