Answer the question
In order to leave comments, you need to log in
How to work with dispatch, functions components and actions in conjunction?
There is a functional component, in which, by clicking on the button, you need to make a request and render new data here.
How to do it right? Dispatch to send in action or resolve in a component?
App.jsx
const InitialPageComponent = () => {
const token = useSelector((state) => state.app.access_token);
const handleClick = () => {
// нужно чтобы токен оказался в store и был отрендерен в этом компоненте.
console.log('getAuthToken', getAuthToken());
};
return (
<div>
<div>{token}</div>
<Button title="Получить токен" onClick={handleClick} />
</div>
);
};
export const setAccessToken = (accessToken) => ({
type: SET_ACCESS_TOKEN,
payload: accessToken,
});
const initialState = {
accessToken: null,
};
export const appReducer = (state = initialState, action) => {
switch (action.type) {
case SET_ACCESS_TOKEN: {
return {
...state,
accessToken: action.payload,
};
}
default: {
return state;
}
}
};
export const getAuthToken = () => setAccessToken('324324');
Answer the question
In order to leave comments, you need to log in
well, if you need to render only in this component , then you don’t need redux at all, but it’s probably better to store the token in the store and send something like this
import { useDispatch } from 'react-redux'
const dispatch = useDispatch()
..
const token = getAuthToken()
dispatch({ type: SET_ACCESS_TOKEN, payload: token })
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question