dan_boy
dan_boy

Reputation: 2009

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

Upvotes: 13

Views: 27313

Answers (1)

Yousaf
Yousaf

Reputation: 29282

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

Upvotes: 26

Related Questions