0
votes

I need to dispatch Redux actions inside React custom hook. How do I obtain the store instance to dispatch actions inside the function? I guess useContext should do the trick, but I'm not sure how to actually use it. Here are code examples

export const useValueInput = (oletusArvo) => {

    const [value, asetaValue] = useState(oletusArvo)
    const [store] = useContext(???)

    const onChange = ({target}) => {
        asetaValue(target.value)
    }

    return [
        value,
        asetaValue,
        {
            value,
            onChange
        }
    ]
}

Upper in the hierarchy I have defined store provider as follows

render() {
    return (
      <div>
        <Provider store={store}>
          <ComponentRouter />
        </Provider>
      </div>
    )
  }
1
If you are using react-redux, they provide a useStore and a useDispatch hook. react-redux.js.org/next/api/hooks#usedispatch - thathat

1 Answers

3
votes

You can use react-redux's Hooks

import { useSelector, useDispatch  } from 'react-redux'

export const ComponentRouter = (props) => {
    // get dispatch function for later use
    const dispatch = useDispatch();
    // get value from the store
    const oldValue = useSelector(state => state.prop.innerProp.value);

    const onChange = ({target}) => {
        dispatch({
            type: SOMETHING_CHANGED,
            value: target.value,
        });
    }

    return <select value={value}>{options.map(....)</select>
};

PS: and then you wrap the component in the Store Provider