Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a action creator in a functional component with react-redux?

I'm learning react-redux. I am struggling a bit with the use of redux in functional components. How do I call an action from a functional component. I have seen some tutorials that use react hooks. Which makes sense to me. But these tutorials call action types and not functions that create action types.

My case:

Wrapping container: Im passing from a wrapping container component that manages all data the necassary props down to the LoadedNavbar function:

<LoadedNavbar isAuthenticated = {isAuthenticated} profile = {profile} />

Functional Component: A Navbar with a button to log out. The logout action should be called in the functional component.How do i make the action creator logout available in this function?

import React, { Component } from "react";
import { logout } from "../../../../actions/auth";
import { Link } from "react-router-dom";

export function LoadedNavbar (props) {

    const {isAuthenticated, profile} = props


  return (

   <div> 

   <button onClick={this.props.logout} className="nav-link btn btn-info btn-sm text-light">Logout</button> 

   </div>

   )
}

Action

// LOGOUT USER
export const logout = () => (dispatch, getState) => {
  axios
    .post(apiBase + "/auth/logout/", null, tokenConfig(getState))
    .then(res => {
      dispatch({
        type: LOGOUT_SUCCESS
      });
    })
    .catch((err) => {
      dispatch(returnErrors(err.response.data, err.response.status));
    });
};

Reducer

export default function(state = initialState, action) {
  switch (action.type) {
    case LOGOUT_SUCCESS:
    default:
      return state;
  }
}
like image 681
dan_boy Avatar asked Aug 16 '20 12:08

dan_boy


People also ask

Can I use useSelector in a function?

We may call useSelector multiple times within a single function component. Each call creates an individual subscription to the Redux store. React update batching behavior will cause multiple useSelector s in the same component to return new value should only return in a single re-render.

Can I use mapDispatchToProps in functional component?

Yes. You can skip the first parameter by passing undefined or null . Your component will not subscribe to the store, and will still receive the dispatch props defined by mapDispatchToProps .

Can I use Redux with functional components?

React is popular for its ability to write functional components. With the React-Redux release, we can use the Hook API to manage the state without using the higher-order components. Thus, we no longer need to add extra components to the component tree.

How do you bind action creators with dispatch function?

bindActionCreators(actionCreators, dispatch) Turns an object whose values are action creators, into an object with the same keys, but with every action creator wrapped into a dispatch call so they may be invoked directly. Normally you should just call dispatch directly on your Store instance.


1 Answers

There are two ways to dispatch actions from functional components:

  • Using mapDispatachToProps function with connect higher order component, same as in class based components.

    For details of how to use mapDispatchToProps along with connect to dispatch actions, see: React Redux - Connect: Dispatching Actions with mapDispatchToProps

  • Using useDispatch hook provided by react-redux.

    If you want to use this hook, then you need to import it from the react-redux package. This hook returns a function that can be used to dispatch actions.

    Example:

    import React from "react";
    import { logout } from "../../../../actions/auth";
    import { useDispatch } from "react-redux";
    
    function LoadedNavbar (props) {
        ...
    
        const dispatch = useDispatch();
    
        const handleClick = () => {
            dispatch(logout());
        }
    
        return (
           <div> 
             <button onClick={handleClick}>Logout</button> 
           </div>
        )
    }
    

    For details of hooks provided by react-redux, see React Redux - Hooks

like image 172
Yousaf Avatar answered Oct 21 '22 06:10

Yousaf