English is not my native language, but I will try to make myself understand my best.
In the axios_cards component I am doing a get by axios to an api json and I assign to another component the list of objects as property
import React, { Component } from 'react';
import axios from 'axios';
import CardsGrid from "../Pages/CardsGrid"
class Axios_cards extends Component {
constructor(props) {
super(props)
this.state = {
courses : []
}
}
componentDidMount() {
axios.get('http://my-json-server.typicode.com/jee4nc/myjsonserver/lista')
.then(response => this.setState({
courses: response.data
}))
}
render() {
const {courses} = this.state
return <CardsGrid courses={courses}/>
}
}
export default Axios_cards;
But in the component to which I assign the properties, it does not recognize the array and does not allow me to map the list
import React from 'react';
import Cards from "../Molecules/Cards"
const CardsGrid = ({courses}) => (
<div className="ed-grid m-grid-3">
{
courses.map( e =>
<Cards
id={e.id}
title={e.title}
description={e.description}
image={e.image}
price={e.price}
key={e.id}
/>)
}
</div>
)
export default CardsGrid;
does not recognize courses to be able to map
TypeError: Cannot read property 'map' of undefined
CardsGrid
src/Components/Pages/CardsGrid.jsx:5
2 | import Cards from "../Molecules/Cards"
3 |
4 | const CardsGrid = ({courses}) => (
> 5 | <div className="ed-grid m-grid-3">
6 | {
7 | courses.map( e =>
8 | <Cards
What if your response.data is null or not an array?
This should resolve it
<div className="ed-grid m-grid-3">
{
Array.isArray(courses)? courses.map( e =>
<Cards
id={e.id}
title={e.title}
description={e.description}
image={e.image}
price={e.price}
key={e.id}
/>) : null
}
</div>
Related
I tried several ways and nothing seems to work :( I'm trying to learn React by building a simple app that implements Socket io and can't find a way to pass "response" as a prop to the child component.
import socketIOClient from "socket.io-client";
import Main from "./Main";
const ENDPOINT = "http://127.0.0.1:4001";
function App() {
const [response, setResponse] = useState([]);
useEffect(() => {
const socket = socketIOClient(ENDPOINT);
socket.on("tick", (data) => {
setResponse(data);
});
}, []);
console.log(response);
return (
<>
<div style={{ textAlign: "center" }}>
<Main
responses = {response}
/>
</div>
</>
);
}
export default App;
import React from 'react';
import './Main.css';
class Main extends React.Component {
render() {
return (
<div className="container">
<div className="placeholder">hello {this.props.responses}</div>
<div className="placeholder"></div>
<div className="placeholder"></div>
</div>
);
}
}
export default Main;
I get this error
×
×
Error: Objects are not valid as a React child (found: object with keys {currencyPairName, prices}). If you meant to render a collection of children, use an array instead.
▶ 22 stack frames were collapsed.
Socket.
src/App.js:14
11 | useEffect(() => {
12 | const socket = socketIOClient(ENDPOINT);
13 | socket.on("tick", (data) => {
> 14 | setResponse(data);
| ^ 15 | });
16 | }, []);
17 |
my response contains an array of objects
hope someone can show me the light..
I am trying to fetch data using React JS and I am having the following error in my console:
Uncaught Error: Objects are not valid as a React child (found: object
with keys {productsList}). If you meant to render a collection of
children, use an array instead.
And here is my code:
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';
class Products extends Component {
constructor(props) {
super(props);
this.state = {
products: []
};
}
//Lifecycle hook
componentDidMount () {
axios.get('/api/storageapp')
.then(response => {
console.log(response)
this.setState({
products: response.data,
})
})
}
render() {
const { products } = this.state;
const productsList = products.length ? (
products.map(product => {
return (
<div key={product.id}>
<div>{product.product_name}</div>
</div>
)
})
) : (
<div>No products were found.</div>
)
return (
{productsList}
);
}
}
export default Products;
if (document.getElementById('products')) {
ReactDOM.render(<Products />, document.getElementById('products'));
}
Any clue what's happening?
Because you're returning an object:
return (
{productsList}
);
You should be returning just productsList. Get rid of the object literal syntax around it.
return productsList;
I am trying to figure out where my error is in my react js page
I have tried different things like changing it into a state component, return and render statements, etc. But its still giving me
"TypeError: Cannot read property 'map' of undefined
Recipes
src/components/Recipes.js:4
1 | import React from "react";
2 |
3 | const Recipes = (props) => (
4 |
5 | { props.recipes.map((recipe)=> {
6 | return (
7 |
View compiled"
App.js
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import InputForm from "./components/InputForm";
import Recipes from "./components/Recipes"
const API_KEY= "mykey";
class App extends Component {
state= {
recipes: []
}
getRecipe = async (e) => {
e.preventDefault();
const recipeName = e.target.elements.recipename.value;
const api_call = await fetch(`https://www.food2fork.com/api/search?key=${API_KEY}&q=${recipeName}&page=2`)
const data = await api_call.json();
this.setState({ recipes: data.recipes });
}
render() {
return (
<div className="App">
<header className="App-header">
React Cookbook
</header>
<InputForm getRecipe={this.getRecipe} />
<Recipes recipes={this.state.recipes} />
</div>
);
}
}
export default App;
Recipes.js
import React from "react";
const Recipes = (props) => (
<div>
{ props.recipes.map((recipe)=> {
return (
<div key={recipe.recipe_id }>
<img src={recipe.image_url} alt={recipe.title}/>
<h3>{ recipe.title }</h3>
</div>
)
})}
</div>
)
export default Recipes;
As Andrew notes in the comments, it sounds like the response from the server is undefined, and that's what is getting added to the recipes state object. You can check for this in the console. Are your API key and recipe name valid, for example? Are you accessing the correct part of the returned data?
As an aside, recipes in state is empty on the first render. You need to check for that possibility in your code. Here I've simply returned an empty div, but you could add a loading spinner or something there instead to provide useful feedback to the user.
render() {
const { recipes } = this.state;
if (!recipes.length) return <div />;
return (
<div className="App">
<header className="App-header">
React Cookbook
</header>
<InputForm getRecipe={this.getRecipe} />
<Recipes recipes={recipes} />
</div>
);
}
I got the object function using in react component, the below is my code, I tried to create an object function inside articleActions object, not got the syntax error. The api import is working fine and I get the right data and store in this component state: this.state.articles, this.state.authors.
App.js
import React from "react";
import DataApi from "../DataApi";
import data from "../testData";
import ArticleList from "./ArticleList";
const api = new DataApi(data.data);
class App extends React.Component {
constructor() {
super();
this.state = {
articles: api.getArticles(),
authors: api.getAuthors()
};
}
articleActions = {
lookupAuthor: authorId => this.state.authors[authorId]
};
render() {
return (
<ArticleList
articles={this.state.articles}
articleActions={this.articleActions}
/>
);
}
}
export default App;
the second file: ArticleList.js
import React from "react";
import Article from "./Article";
const ArticleList = props => {
return (
<div>
{Object.values(props.articles).map(article => (
<Article
key={article.id}
article={article}
actions={props.articleActions}
/>
))}
</div>
);
};
export default ArticleList;
the third file: Article.js
import React from "react";
const Article = props => {
const { article, actions } = props;
const author = actions.lookupAuthor(article.authorId);
return (
<div>
<div>{article.title}</div>
<div>{article.date}</div>
<div>
<a href={author.website}>
{author.firstName} {author.lastName}
</a>
</div>
<div>{article.body}</div>
</div>
);
};
export default Article;
The error message is :
SyntaxError: C:/Users/coral/Documents/react-advanced/lib/components/App.js:
Unexpected token (16:17)
14 | };
15 | }
> 16 | articleActions = {
| ^
17 | lookupAuthor: authorId => this.state.authors[authorId]
18 | };
the lookupAuthor should be a function with parameter:authorId, and get the return value of the author object. this.state.authors is the array of author objects. Each object with the authorId as the key, and author object as the value. I am not sure what is the error here when declare the function inside the js object. Hope someone can help
That should be method:
articleActions = () => ({
lookupAuthor: authorId => this.state.authors[authorId]
});
single.js :
import React, { Component } from 'react';
import Details from '../components/details'
import { ProgressBar } from 'react-materialize';
import { Route, Link } from 'react-router-dom';
const Test = () => (
<div> RENDER PAGE 1</div>
)
class SinglePage extends Component {
constructor(props) {
super(props);
this.state = {
data: null,
}
}
componentDidMount() {
fetch('http://localhost:1337/1')
.then((res) => res.json())
.then((json) => {
this.setState({
data: json,
});
});
}
render() {
const { data } = this.state;
return (
<div>
<h2> SinglePage </h2>
{!data ? (
<ProgressBar />
) : (
<div>
<Details data={data} />
</div>
)}
</div>
);
}
}
export default SinglePage;
details.js :
import React, { Component } from 'react';
import PropTypes from 'prop-types';
class Details extends Component {
static propTypes = {
item: PropTypes.shape({
date: PropTypes.string.isRequired,
}).isRequired,
}
render() {
const { item } = this.props;
return (
<div>
<p> {item.date} </p>
</div>
)
}
}
export default Details;
In console, I am getting an error : Warning: Failed prop type: The prop item is marked as required in Details, but its value is undefined.
From this I though my json was not catched but I have an other component which fetch on http://localhost:1337/ , get datas and display them correctly, and going to http://localhost:1337/1 send me a json response so I'm quite confused here.
Additional screenshot :
SinglePage is passing date props with name data as oppose to item that is defined in Details
<Details item={date} />
Also adding init value for date
constructor(props) {
super(props);
this.state = {
date: { date: null },
}
}