D
D
depstor2020-10-08 22:47:06
React
depstor, 2020-10-08 22:47:06

Why does it give an error when writing to state?

action

export const fetchQuote = url => {
    return dispatch => {
        fetch(url)
            .then(res => res.json())
            .then(res => dispatch({ type: 'quote', data: res }))
    }
}


reducer
const initialState = {
    company: [],
    quote: []
}

export const getChares = (state = initialState, action) => {
    switch (action.type) {
        case 'company':
            console.log('company', action.data)
            return {
                ...state,
                company: action.data
            }
        case 'quote':
            console.log('quote', action.data)
            return {
                ...state,
                quote: action.data
            }
        default:
            return state
    }
}


component
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { fetchQuote } from '../../Redux/actions/actions';
import { __apiKey, __apiRealTime } from '../../__apis/__apis';

class RealTimeQuote extends Component {

    componentDidMount() {
        this.props.fetchQuote(__apiRealTime + __apiKey);

    }

    render() {
        console.log('dfgvbd', this.props.quote)

        const test = this.props.quote.map((res, i) => {
            return (
                <li key={i}>{res.volume}</li>
            )
        })

        return (
            <div>
                <ul>
                    {test}
                </ul>
            </div>
        )
    }
}


export default connect(state => (
    {
        quote: state.fetchQuote.quote
    }
), { fetchQuote })(RealTimeQuote)


error text:
TypeError: Cannot read property 'quote' of undefined
swears at: {
quote: state.fetchQuote.quote
}

while there is another api call exactly the same way and everything works out

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Pavel Shvedov, 2020-10-08
@depstor

There is no fetchQuote field in state, there is just state.quote

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question