0

I have this json format when I console.log(notes) :

{
  "document_tone": {
    "tone_categories": [
      {
        "tones": [
          {
            "score": 0.027962,
            "tone_id": "anger",
            "tone_name": "Colère"
          },
          {
            "score": 0.114214,
            "tone_id": "sadness",
            "tone_name": "Tristesse"
          }
        ],
        "category_id": "emotion_tone",
        "category_name": "Ton émotionnel"
      },
      {
        "tones": [
          {
            "score": 0.028517,
            "tone_id": "analytical",
            "tone_name": "Analytique"
          },
          {
            "score": 0,
            "tone_id": "tentative",
            "tone_name": "Hésitant"
          }
        ],
        "category_id": "language_tone",
        "category_name": "Ton de langage"
      },
      {
        "tones": [
          {
            "score": 0.289319,
            "tone_id": "openness_big5",
            "tone_name": "Ouverture"
          },
          {
            "score": 0.410613,
            "tone_id": "conscientiousness_big5",
            "tone_name": "Tempérament consciencieux"
          },
          {
            "score": 0.956493,
            "tone_id": "emotional_range_big5",
            "tone_name": "Portée émotionnelle"
          }
        ],
        "category_id": "social_tone",
        "category_name": "Ton social"
      }
    ]
  },
  "idMedia": 25840
}

this a picture of the console.log(notes), I don't know why I am getting an empty array besides the expected results

enter image description here

but when I try to map tone_categories I get this error :

TypeError: Cannot read property 'map' of undefined

this is the code I've built so far :

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      notes: [],
    };
  }

componentWillMount() {
  fetch('http://localhost:3000/api/users/analyzeMP3?access_token=GVsKNHWnGWmSZmYQhUD03FhTJ5v80BjnP1RUklbR3pbwEnIZyaq9LmZaF2moFbI6', { 
    method: 'post', 
    headers: new Headers({
      'Authorization': 'Bearer', 
      'Content-Type': 'application/x-www-form-urlencoded'
    }), 
  })
    .then(response => response.text())
    .then(JSON.parse)
    .then(notes => this.setState({ notes }));
}

render() {
  const { notes } = this.state;
  console.log('notes',notes)

  return (

    <div className="App">
     {notes !== undefined && notes !== "" &&  notes !== [] ? notes.document_tone.map((tone_categories, idx) => {
    {console.log('notes',notes.document_tone[tone_categories].category_name)}
     }) : null}  

      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}

}

export default App;
2
  • use componentDidMount instead of componentWillMount Commented Sep 23, 2019 at 14:38
  • 5
    componentWillMount() is deprecated, use componentDidMount() instead and make sure your render() function checks if notes is undefined. By the way, notes !== [] will always be true. Commented Sep 23, 2019 at 14:39

4 Answers 4

1

Your initial state is notes: [], so the array will by empty during the first render and if you try to access an item from an empty array, you get the error.

A better approach in this case would be to have a loading state and defer the render until you have the data fetched:

class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      notes: [],
      loading: true // Set the loading to true initially
    };
  }

  componentDidMount() {
    fetch(
      "http://localhost:3000/api/users/analyzeMP3?access_token=GVsKNHWnGWmSZmYQhUD03FhTJ5v80BjnP1RUklbR3pbwEnIZyaq9LmZaF2moFbI6",
      {
        method: "post",
        headers: new Headers({
          Authorization: "Bearer",
          "Content-Type": "application/x-www-form-urlencoded"
        })
      }
    )
      .then(response => response.text())
      .then(JSON.parse)
      .then(notes => this.setState({ notes, loading: false })); // reset the loading when data is ready
  }

  render() {
    const { notes, loading } = this.state;
    console.log("notes", notes);

    return loading ? (
      <p>Loading...</p> // Render the loader if data isn't ready yet
    ) : (
      <div className="App">//...</div>
    );
  }
}
Sign up to request clarification or add additional context in comments.

Comments

1

The problem is with this condition notes !== [] which will always return true. If you need to check if an array is empty you can use array.length === 0. Also use componentDidMount instead of componentWillMount because componentWillMount is deprecated.

You can do something like

return (
    <div className="App">
      {
        notes && notes.length > 0 ? 
        notes.document_tone.map((tone_categories, idx) => {
            return notes.document_tone[tone_categories].category_name;
        }) : null
      }
    </div>
  );

Comments

0

That is because initially notes as an empty array & does not have document_tone key. So this line will throw error notes.document_tone.map

Add a condition and check if notes have document_tone.

<div className="App">
     {
notes !== undefined && notes !== "" &&  notes !== [] && notes.document_tone.length >0 ?
notes.document_tone.map((tone_categories, idx) => {
    {console.log('notes',notes.document_tone[tone_categories].category_name)}
     }) :
     null}  

Comments

0

When you start your application, then the constructor runs, you set the state with notes=[], a render() occurs and prints it in the console.

Then, after willComponentMount(), notes has a new value and triggers a new render().

Comments

Your Answer

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