Rendering json data with axios
axios, json, reactjs
Solution
Here's my answer to the exercise given. I would like to share this, since you have tried that out. There may be different ways of doing this. Follow your own way. Here's how I did it.
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';
import _ from 'lodash';
class Data extends Component {
constructor(props) {
super(props);
this.state = {
array: []
};
this.renderRecipes = this.renderRecipes.bind(this);
}
componentDidMount(){
axios
.get('https://s3-us-west-2.amazonaws.com/digicode-interview/Q1.json')
.then(({ data })=> {
console.log(data);
this.setState(
{ array: data.recipes }
);
})
.catch((err)=> {})
}
render() {
console.log(this.state.array);
return(
<div>
<h3>Recipes</h3>
<ul className="list-group">
{this.renderRecipes()}
</ul>
</div>
);
}
renderRecipes() {
console.log(this.state.array);
return _.map(this.state.array, recipe => {
return (
<li className="list-group-item" key={recipe.name}>
{recipe.name}
<ul className="list-group">
Ingredients:
{this.renderIngredients(recipe)}
</ul>
</li>
);
});
}
renderIngredients(recipe) {
return _.map(recipe.Ingredients, ingredient => {
return (
<li className="list-group-item" key={ingredient.name}>
<p>Name: {ingredient.name}, Amount: {ingredient.amount}</p>
</li>
);
});
}
}
export default Data;
Problem
I'm trying to get data from .json file. Nothing appears on the page. Maybe somebody have an idea why? Thanks! This is link on the file https://s3-us-west-2.amazonaws.com/digicode-interview/Q1.json ``` import React from 'react'; import createReactClass from 'create-react-class'; import ReactDOM from 'react-dom'; import axios from 'axios'; class Data extends React.Component { constructor(props) { super(props); this.state = { array: [] }; } componentDidMount(){ axios .get('https://crossorigin.me/https://s3-us-west-2.amazonaws.com/digicode-interview/Q1.json') .then(({ data })=> { this.setState({ array: data.recipes.Ingredients }); }) .catch((err)=> {}) } render() { const child = this.state.array.map((element, index) => { return <div key={index}> <p>{ element.data.name }</p> </div> }); return <div><div>{ child }</div></div>; } } export default Data; ```