everyone! I'm faced with the problem that my component is rendered twice. I found out that it happens because of using useEffect and useSelector at the same time, but I don't know how to fix it. I'm not using React.StrictMode.
import React, {useEffect, useMemo, useState} from "react";
import {useIntl} from "react-intl";
import Typography from "../../../components/Typography";
import Card from "../../../components/Card";
import CardTitle from "../../../components/CardTitle";
import {useDispatch, useSelector} from "react-redux";
import songActions from 'app/actions/song'
function List() {
const dispatch = useDispatch();
const {
formatMessage,
} = useIntl();
useEffect(() => {
dispatch(songActions.fetchSongs());
}, [])
const reduxState = useSelector((store) => store);
console.log(reduxState);
return (
<>
<Typography>
{formatMessage({ id: 'title' })}
</Typography>
{/*<div>*/}
{/* { songs.map(item => {*/}
{/* <Card>*/}
{/* <CardTitle>*/}
{/* ${item.id}*/}
{/* </CardTitle>*/}
{/* </Card>*/}
{/* })}*/}
{/*</div>*/}
</>
);
}
export default List;
I've tried to use useRef in useUpdateEffect.js like this:
import { useEffect, useRef } from "react"
export default function useUpdateEffect(callback, dependencies) {
const firstRenderRef = useRef(true)
useEffect(() => {
if (firstRenderRef.current) {
firstRenderRef.current = false
return
}
return callback()
}, dependencies)
}
And it is not render component twice but my data is not fetching because of this.
CHANGED!
Well, I figured out the double-loading error, but then another one appeared. This code should display cards with the values of objects with redux state. But an empty div is displayed. How can I fix it?
Here is the updated code of component:
import React, {useEffect} from "react";
import {useIntl} from "react-intl";
import Typography from "../../../components/Typography";
import Card from "../../../components/Card";
import CardTitle from "../../../components/CardTitle";
import {useSelector} from "react-redux";
function List() {
const {
formatMessage,
} = useIntl();
useEffect(() => {
console.log('Hello');
}, [])
const songs = useSelector((store) => store.song.songs);
return (
<>
{}
<Typography>
{formatMessage({ id: 'title' })}
</Typography>
<div>
{songs.map(item => {
<Card>
<CardTitle>
${item.id}
</CardTitle>
</Card>
})}
</div>
</>
);
}
export default List;
You have missed something there in map function.
you should write like this.
{songs.map(item => (
<Card>
<CardTitle>
{item.id}
</CardTitle>
</Card>
))}