Umbro
Umbro

Reputation: 2204

Calling the second function after calling the first function and fetching the data, react + redux

In pure React, I call the clickActive function in thegetTodos function after fetching the data from the server.

  getTodos = () => {
    const url = 'https://jsonplaceholder.typicode.com/todos';

    const params = {
      expand: 'createdBy, updatedBy'
    };

    axios({
      method: 'GET',
      url,
      params
    })
      .then(res => {
        this.setState({
          todos: res.data
        }, () => this.clickActive());
      })
      .catch(error => {
        console.log(error);
      });
  };


clickActive = () => {
  const activeTask = document.querySelector('.activeTask');

  activeTask.click();
  console.log('active')
};

How call function clickActive in React + Redux? I create the getTodos action in theactions folder. In the Todos component it calls this functiongetTodos by clicking the GET button. How to call the clickActive function after fetching the data? I put the clickActive function in thehelpers file. Should I import the clickActive function into the file actions/index.js?

Expected effect: click button GET -> call functiongetTodos -> call function clickActive

Demo here: https://stackblitz.com/edit/react-rk1evw?file=actions%2Findex.js

actions

import axios from 'axios';

export const GET_TODOS = 'GET_TODOS';
export const FETCH_SUCCESS = 'FETCH_SUCCESS';
export const FETCH_FAILURE = 'FETCH_FAILURE';

export const getTodos = () => 
dispatch => {

  return axios({
      url: 'https://jsonplaceholder.typicode.com/todos',
      method: 'GET',
    })
    .then(({data})=> {
      console.log(data);

      dispatch({type: GET_TODOS, payload:{
        data 
      }});   
    })
    .catch(error => {
      console.log(error);

      dispatch({type: FETCH_FAILURE})
    });
};

export const getTodo = () => 
dispatch => {

  return axios({
      url: 'https://jsonplaceholder.typicode.com/todos',
      method: 'GET',
    })
    .then(({data})=> {
      console.log(data);

      dispatch({type: GET_TODOS, payload:{
        data 
      }});   
    })
    .catch(error => {
      console.log(error);

      dispatch({type: FETCH_FAILURE})
    });
};

Todos

import React, { Component } from 'react';
import { connect } from 'react-redux';
import {getTodos} from '../.././actions';
import { clickActive } from '../../helpers';

class Todos extends Component {
  constructor(props){
    super(props);
  }

  render() {
    return (
      <>
        <button onClick={this.props.getTodos}>GET</button>
        <ul>
          {this.props.todos.map(todo => {
          return <li key={todo.id}>
                    {todo.title}
                </li>
          })}
        </ul>
        <div className="active">Active</div>
      </>
    );
  }
}

const mapStateToProps = state => {
  const { todos } = state;

  return {
    todos
  };
};

const mapDispatchToProps = dispatch => ({
  getTodos: () => dispatch(getTodos())
});

export default connect(mapStateToProps, mapDispatchToProps)(Todos);

helpers

export const clickActive = () => {
  const activeTask = document.querySelector('.active');

  activeTask.click();

  console.log('click div');
};

Upvotes: 0

Views: 98

Answers (1)

lavor
lavor

Reputation: 1877

Your clickActive function is a function that will interacts with created DOM, hence it should be called after render in componentDidUpdate and componentDidMount (or in useEffect hook if you would use hooks).

In componentDidMount/componentDidUpdate scenario I suggest add this those lifecycle methods in your Todos component:

componentDidMount() {
    // call clickActive once after mount (but your todos are probably empty this time)
    clickActive();
}

componentDidUpdate(prevProps) {
    if (prevProps.todos !== this.props.todos) {
        // call clickActive every time when todos is changed
        // (i.e. it will be called when your asynchronous request change your redux state)
        clickActive();
    }
}

Upvotes: 1

Related Questions