Reputation: 1
I'm new to react and trying to learn by building this simple app. I want to expose data from parent app in a child component but my result in the component appears to be empty. what should I do to get the result to appear and re-render in the child component?
import React, { useState, useEffect } from "react";
import socketIOClient from "socket.io-client";
import Main from "./Main";
import Response from "./response"
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
responseCurrency = {response.map(memb => <div>{memb.currencyPairName}</div>)}
dataObject = {response}
/>
</div>
</>
);
}
export default App;
import './Main.css';
function Main(props) {
const [result, setResult] = React.useState(props.dataObject);
React.useEffect(() => {
console.log(result)
setResult(result);
}, [result]);
return <div className="container">
{result[0]}
<div id="palceholder1" className="placeholder">hello</div>
<div id="palceholder2" className="placeholder"></div>
<div id="palceholder3" className="placeholder"></div>
</div>;
}
export default Main;
I am a beginner in ReactJS, so I'm lost at the moment. Hope someone could shed a light.. Thanks in advance
Gali
Upvotes: 0
Views: 47
Reputation: 85201
function Main(props) {
const [result, setResult] = React.useState(props.dataObject);
The problem is that you're copying props into state. The above line of code says to create a new state for Main, who's initial value is props.dataObject. When props.dataObject changes later, nothing will happen to this state.
Instead, you should use the prop directly:
function Main(props) {
return (
<div className="container">
{props.dataObject[0]}
<div id="palceholder1" className="placeholder">
hello
</div>
<div id="palceholder2" className="placeholder"></div>
<div id="palceholder3" className="placeholder"></div>
</div>
);
}
Upvotes: 1