简体   繁体   中英

React - Redux wait fetch result before render component

I have some react-redux project. I have some component which i wan't to list some data from api. simply i dispatch action from my component inside of componentDidMount method, which fetch data.

When i refresh page i make console.log my redux state.

Component rendering well but when i look at the console there is my console.log show my state empty then show my state normally.. In this progress time my component give me error that my data which i wan't to show on page is undefined.

So here is because fetch method working async how i understand, but what need to do for when my redux state will get data from api then component will be rendered?

here is my action:

export const FETCH_DATA_START = 'FETCH_DATA_START'
export const FETCH_DATA_SUCCESS = 'FETCH_DATA_SUCCESS'
export const FETCH_DATA_FAILED = 'FETCH_DATA_FAILED'

export const getData = () => {
    return (dispatch) => {
        dispatch({
            type: FETCH_DATA_START
        })
        fetch("http://api.com", {
                credentials: "include",
                method: "POST",
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                }
            })
            .then(res => res.json())
            .then((res) => {
                dispatch({
                    type: FETCH_DATA_SUCCESS,
                    payload: res
                })
            })
            .catch((err) => {
                console.log(err)
                dispatch({
                    type: FETCH_DATA_FAILED,
                    payload: 'error'
                })
            })
    }
}

here is my reducer:

import { FETCH_DATA_START, FETCH_DATA_SUCCESS, FETCH_DATA_FAILED } from 'store/actions/getData'

let initialState = []

export default (state = initialState, action) => {
    switch (action.type) {
        case FETCH_DATA_START:
            return [...state]
        case FETCH_DATA_SUCCESS:
            return [...state, ...action.payload]    
        case FETCH_DATA_FAILED: 
            return [state]
        default:
            return state
    }
}

in my component:

import React, {Component} from 'react'
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux'
import {getData} from 'store/actions/getData'


class Ops extends Component {

    componentDidMount() {
        this.props.getData()
    }
    render() {
       console.log(this.props.dataOps)
       return(
           <div></div>
         )
    }
}


const mapStateToProps = state => ({dataOps: state.dataOps})

function mapDispatchToProps(dispatch) {
    return {
        getData: bindActionCreators(getData, dispatch)
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(Ops)

Option 1

check the reducer state before use

Option 2

 async componentDidMount(){
   //set loader true
   await this.props.getData;
   //set loader false
 }

You could implement a 'loading' state

import React, {Component} from 'react'
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux'
import {getData} from 'store/actions/getData'


class Ops extends Component {

    state = {
      isLoading: true
    }

    componentDidMount() {        
        this.props.getData().then(res => res.json())
        .then((res) => {
            // Toggle state after promise completed
            this.setState({
              isLoading: false
            })  

            // Dispatch data
            dispatch({
                type: FETCH_DATA_SUCCESS,
                payload: res
            })
        })
        .catch((err) => {
            console.log(err)
            dispatch({
                type: FETCH_DATA_FAILED,
                payload: 'error'
            })
        })
    }
    }

    render() {     
      // If we're still loading data, show loading component
      if (this.state.isLoading) {
        return (<div>Loading...</div>);
      }

      console.log(this.props.dataOps)

      // Render with data
      return(
          <div>Loading completed!</div>
      )
    }
}


const mapStateToProps = state => ({dataOps: state.dataOps})

function mapDispatchToProps(dispatch) {
    return {
        getData: bindActionCreators(getData, dispatch)
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(Ops)

edit; return the promise instead of the resolved data; (Not sure about syntax)

export const getData = () => {
    return (dispatch) => {
        dispatch({
            type: FETCH_DATA_START
        });

        return fetch("http://api.com", {
            credentials: "include",
            method: "POST",
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            }
        })
    })
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM