I want to display response of axiosInstance.get. I got response but it is not displayed. Can you help me to find a solution?
export default function Tour() {
const { slug } = useParams();
const classes = useStyles();
const [data, setData] = useState({ tours: [] });
useEffect(() => {
axiosInstance.get('tours/?slug=' slug).then((res) => {
const singleTour = res.data
setData({ tours: singleTour });
console.log(res.data);
});
}, [setData]);
return (
<Container component="main" maxWidth="md">
<CssBaseline />
<div className={classes.paper}></div>
<div className={classes.heroContent}>
<Container maxWidth="sm">
<Typography
component="h1"
variant="h2"
align="center"
color="textPrimary"
gutterBottom
>
{data.tours.title}
</Typography>
<Typography
variant="h5"
align="center"
color="textSecondary"
paragraph
>
{data.tours.description}
</Typography>
</Container>
</div>
</Container>
);
}
There are no errors in network, but nothing is displayed in frontend
output of console.log(res.data)
0:
author: 1
description: "yoga yoga yoga yoga yoga"
end_date: "2022-01-15T14:25:31Z"
id: 1
reg_end_date: "2022-01-15T14:25:36Z"
reg_start_date: "2022-01-15T14:25:33Z"
slug: "tour"
start_date: "2022-01-15T14:25:30Z"
status: 2
title: "new yoga tour"
CodePudding user response:
If the response is always an array of length one then I wouldn't bother storing it in state as an array. Store it as an object, which matches how it's accessed in the render and maintains a state invariant.
export default function Tour() {
...
const [data, setData] = useState({ tours: {} }); // <-- use object
useEffect(() => {
axiosInstance.get('tours/?slug=' slug).then((res) => {
const [singleTour] = res.data; // <-- array destructuring assignment
setData({ tours: singleTour });
console.log(res.data);
});
}, [setData]);
return (
<Container component="main" maxWidth="md">
...
<Container maxWidth="sm">
<Typography ... >
{data.tours.title}
</Typography>
<Typography ... >
{data.tours.description}
</Typography>
</Container>
</div>
</Container>
);
}
