0

I've couldn't find answer on google so I though you guys might help me out.

So I've tried componentWillMount(), componentDidMount() but it appears substring method gets called before I received fetched string.

import React, { Component } from 'react';
import axios from "axios";

class Home extends Component {
    constructor(props){
        super(props);
        this.state = {
            reminders: [{}],
            test: "test"
        };
    }

    getReminders(){
        fetch('/api/reminder/',{method:"GET"}).then(resp => resp.json()).then(data => 
            this.setState({reminders:data}));
    }

    componentWillMount(){
        this.getReminders();
    };

    render() {
        return (
            <div className="main-table">
                { this.state.reminders.map((x,i) => 
                <div key={i} className="table-item">
                    <div className="item-name">{x.title}</div>
                    <div className="item-content flex">
                        <div className="time">{x.from.substr(11,2)} - {x.to}</div>
                        <div className="location">{x.location}</div>
                    </div>
                </div>) }
            </div>
        );
    }
}

export default Home;
1
  • 2
    Initialize your reminders array to an empty array instead of an array with an empty object. Commented Aug 13, 2018 at 19:56

2 Answers 2

2

Take the empty object out of reminders in state so the array has no initial length

That is giving the array a length of 1 to start with and the properties you are looking for inside map() don't exist on that specific object

    this.state = {
        reminders: [],
        test: "test"
    };
Sign up to request clarification or add additional context in comments.

Comments

1

The reason is that you initialize this.state.reminders with not empty array, but with array with empty object, which caused err when you are accessing it props You can either initialize with empty array, e.g.

this.state = {
        reminders: []
}

Or you can add some property, e.g. isRemindersLoaded which initially set to false, and only render table after it has been set to true, e.g:

this.setState({reminders:data, isRemindersLoaded: true}));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.