How do I set the state with local dynamic json?

Asked

Viewed 55 times

0

How do I place json data within the "recipes[]" array that is in the state?

 import recipes from '../receitas/recipes.json'

 constructor(props) {
    super(props);

    this.recipes = recipes.results;  //json dinâmico local   
    this.state = { 
      receitas: [],     
      searchString: ''        
    };
  } 

  componentDidMount(){    
     this.loadReceitas();
  }

  loadReceitas = async () => {
    const recipesList = await this.props.recipes.results;   
    this.setState({ receitas: recipesList.recipes.results });
  }

From now on I thank anyone who can help me.

2 answers

0


If JSON will be outside the folder src, for example in public, you should get it through an Xmlhttprequest request, possibly using the function fetch.

import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

class App extends React.Component {
  constructor() {
    super();

    this.state = {
      receitas: [],
      searchString: ""
    };
  }

  componentDidMount() {
    this.loadReceitas();
  }

  loadReceitas = async () => {
    const response = await fetch("receitas/recipes.json");
    console.log("response:", response);
    const recipesList = await response.json();
    console.log("json:", recipesList);

    this.setState({ receitas: recipesList.results });
  };

  render() {
    const { receitas } = this.state;
    const valores = Array.isArray(receitas) ? (
      <ul>
        {receitas.map(elemento => (
          <li>{elemento}</li>
        ))}
      </ul>
    ) : (
      <spam>recipe errado!!!</spam>
    );

    return (
      <div className="App">
        <h1>Conteúdo de recipes</h1>

        {valores}
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Example working on Codesandbox.

0

You can simply pass the Recipes within this.state in the constructor. As follows:.

constructor(props) {
    super(props);

    this.recipes = recipes.results;  //json dinâmico local   
    this.state = { 
      receitas: this.recipes,     
      searchString: ''        
    };
  } 

Browser other questions tagged

You are not signed in. Login or sign up in order to post.