Reputation: 5
In my react app I want to fetch data from server and to show it as list.
server returns json like:
{
"files":["a.txt","b.txt","c.txt"]
}
my code looks like:
import React ,{ Component }from "react";
import ReactPlayer from "react-player";
import ListGroup from "react-bootstrap/ListGroup";
import "bootstrap/dist/css/bootstrap.css";
function Watch() {
const cardContent = {
display: "flex",
flexDirection:"row",
alignItems: "center" ,
justifyContent: 'flex-end',
cursor:'pointer'
};
const gridConainer={
display:'grid',
gridTemplateColumns: 'auto auto'
};
getFiles();
let state;
function getFiles(){
fetch("http://localhost:5000/get_videos_list")
.then(res => res.json())
.then(
(result) => {
state=result;// < --- here I'm taking the array from server
},
(error) => {
console.log(error);
}
)
}
return (
<React.Fragment>
<ul className="list-group">
{state.files.map(listitem => (
<li className="list-group-item list-group-item-primary">
{listitem}
</li>
))}
</ul>
</React.Fragment>
);
}
export default Watch;
But I'm getting error:
TypeError: Cannot read property 'files' of undefined
When I enter haedcoded like:
let state = {
files: ["Spring", "Summer", "Fall"]
};
The error is gone and the list created. but the with the hardcoded data and not the data from the server
Upvotes: 0
Views: 245
Reputation: 1985
Try using the useState
hook.
import React ,{ useState } from "react";
//Rest of the imports...
function Watch() {
const [state, setState] = useState({});
//Rest of the code...
//let state; => remove this
function getFiles(){
fetch("http://localhost:5000/get_videos_list")
.then(res => res.json())
.then(
(result) => {
setState(result);
},
(error) => {
console.log(error);
}
)
}
//Rest of the code...
}
Upvotes: 2