L
L
lexstile2020-05-19 18:51:51
React
lexstile, 2020-05-19 18:51:51

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

spoiler
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>
  );
};

actions.js
spoiler
export const setAccessToken = (accessToken) => ({
  type: SET_ACCESS_TOKEN,
  payload: accessToken,
});

reducer.js
spoiler
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;
    }
  }
};

getAuthToken
spoiler
export const getAuthToken = () => setAccessToken('324324');

Answer the question

In order to leave comments, you need to log in

1 answer(s)
H
hzzzzl, 2020-05-19
@hzzzzl

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 question

Ask a Question

731 491 924 answers to any question