Cannot read properties of undefined (reading 'first') - reactjs

I am trying to add data to a dynamic form in antd.
I get the data from firebase and use useEffect to get it.
When I try to run my code I get the error TypeError: Cannot read properties of undefined (reading 'first')
This error happened while generating the page. Any console logs will be displayed in the terminal
Here is what I have
const availablelinks = {
links: [
alllinks
]
};
<Form.List name="links" initialValue={
availablelinks.links.map((item) => {
console.log(item[0])
const lol = item[0]['first']
const zol = 'zol'
return {
first: lol,
last: zol,
};
}, [])
}>
here is the rest of my code https://wtools.io/paste-code/bEEc .
I think that the error has something to do with the useEffect (because when I edit the code and next.js updates the code in the browser there is nothing happening but when I refresh I get the error)
For reference here is how the form looks :
Now i am using
const [theArray, setTheArray] = useState([]);
... (see full code)
<Form.List name="links" initialValue={
theArray.map((item) => {
console.log(item)
const lol = item.first
const zol = item.last
return {
first: lol,
last: zol,
};
}, [])
}>
and I get https://imgur.com/a/WZIzNMo (it kinda works)
it get the state when it is changes but the form does not update

Related

react facing error when want to get specific value from back-end

I am trying to get value from the back-end, it shows totally fine and grabs all the properties in the console, but when I want to access a particular value it shows an error, but sometimes it's working I have tried with useEffect dependencies but still same,
the error is: Uncaught TypeError: Cannot read properties of undefined (reading 'eventName')
example JSON format:
0:{
eventFeeStudent: "34"
eventName: "New event"
eventNotificationsDate: "2022-05-23T18:00:00.000Z"
}
here it's working fine but when want to catch any specific key pair like eventName I am getting error.
const EventEditNavbar = () => {
const { user } = useAuth();
const [userInfo, setUserInfo] = useState({});
console.log(userInfo);
console.log(user);
// console.log(userInfo[0].eventName);
const eventName = userInfo[0].eventName;
useEffect(() => {
if (!user || !user.email) return
const uri = `http://localhost:5000/findevents/?userEmail=${user.email}`;
fetch(uri)
.then((res) => res.json())
.then((data) => setUserInfo(data));
}, [user]);
return (
<Container>
<div className="eventEdit_nav">
<div className="eventEdit_nav_right">
<Link to={`/festivals/${eventName}`}>View</Link>
<Link to="/">Edit</Link>
<Link to="">Manage</Link>
<Link to="">Marketing</Link>
</div>
<div className="eventEdit_nav_left">
<Link to="">Save</Link>
<Link to="">List Event</Link>
</div>
</div>
</Container>
);
};
export default EventEditNavbar;
Keep in mind whenever an object's property is undefined accessing its child will throw an uncaught error, which means there is nothing beneath an undefined property.
In your case, you are initiating the userInfo with an empty object ({}), so the userInfo[0] in the first place (when there are no data fetched from the server) will be undefined and it will throw an error when you try to access its child. To solve this you can use optional chaining, whenever you try something like this.
So doing this will solve your issue:
const eventName = userInfo[0]?.eventName;
/* Whenever userInfo is undefined the eventName will
be set to undefined as well and it will prevent the
application from throwing an error when you try to
access userInfo child */

Sorting data from an API (redux-toolkit)

I'm building a crypto app with react and redux-toolkit.
I'm trying to find a way to manage the data from the API. More specifically i want to be able to sort by value, volume, etc. and add an "isFavourite" property for each coin but i think (correct me if i'm wrong) that the only way to do this is by copying the data to another state. What i've tried so far was adding another state where i passed the data like this:
const [list, setList] = useState()
useEffect(() => {
setList(data)
}, [data])
//"const coinData = list?.data?.coins" instead of "const coinData = data?.data?.coins"
but then an error occured because the data on the "list" were "undefined".
The code bellow is the one that is running without any problems. How can i manage the API data? Am i on the right path or is there a more slick way to do what i want? Thank you!
function Main () {
const { data, error, isFetching } = useGetCryptosQuery()
if(isFetching) return 'Loading...'
const globalStats = data?.data?.stats
const coinData = data?.data?.coins
const coinList = coinData.map(coin => {
return (
<Coin
price = {coin.price}
key = {coin.uuid}
id = {coin.uuid}
name = {coin.name}
icon = {coin.iconUrl}
/>)
})
return (
<div>
<h2>Main</h2>
{coinList}
</div>
)
}
export default Main
You are on the right track - I set up something similar and added a check for null trying to map the data, and that avoids the error you probably got.
const coinList = coinData ? coinData.map((coin) => {
///...coin component
}) : <div></div>;
Then, instead of an error for undefined data, it will return an empty div - until the data is there, then it will render ok.

Server Error TypeError: Cannot read properties of undefined (reading 'content')

const Post = () => {
const router = useRouter();
const slug = router.query.postslug;
const currentPost = PostData.find((post) => post.slug === slug);
return (
currentPost.content
)
}
export default Post;
Server Error
TypeError: Cannot read properties of undefined (reading 'content')
Below is the array of objects
const PostData = [
{
id:1,
slug:...,
content:...
}
]
The problem is that content is undefined in context of currentPost.
Its undefined because PostData doesnt match the slug.
a quick guard should help the solution
{ currentPost && currentPost.content}
I recommend preparing for it not finding anything like this:
currentPost?.content
If you believe this shouldn't give an error ever, as you haven't said this, feel free to return with a comment/edit describing your problem a bit more.

React and Apollo useMutation --- Cannot read property '0' of undefined

Can't seem to figure out away to handle this when the page loads. I continually get the error 'TypeError: Cannot read property '0' of undefined' when I load the component. The useMutation is using the react-apollo library, but for some reason it is checking if causes[0].name exists before we even run the mutation. The cause_name is initially empty on page load, but then first becomes undefined when we first interact with DonateBox. However then when we set a cause value, it correctly sends the array. So I'm not sure why this error continues to persist? Even if it is undefined, it shouldn't be complaining right? Any help would be great, it's driving me crazy.
const DonatePage = () => {
const [causes, setCauses] = useState('')
const [category, setCategory] = useState('cause')
const [amount, setAmount] = useState('25')
const [frequency, setFrequency] = useState('once')
const [saveDonation] = useMutation(CREATE_DONATION, {
variables: {
date: moment().toDate(),
type: 'cause',
recurring: 'false',
amount: Number(amount),
cause_name: undefined || null ? undefined : causes[0]?.name
},
onCompleted() {
}
})
return (
<DonateBox
goToPayment={setCurrentPage}
setCauseProps={setCauses}
setAmount={setAmount}
setCategory={setCategory}
/>
)
}
Pass your variables to the mutation when you call the mutation function. And remove variables from your useMutation() options.
const [saveDonation] = useMutation(CREATE_DONATION, {
onCompleted() {
}
});
...
...
...
saveDonation({
variables: {
date: moment().toDate(),
type: 'cause',
recurring: 'false',
amount: Number(amount),
cause_name: undefined || null ? undefined : causes[0].name
}
})

Why do I get undefined value from async function?

I have been using Google firestore as a database for my projet.
In the collection "paths", I store all the paths I have in my app, which are composed of 2 fields : name, and coordinates (which is an array of objects with coordinates of points).
Anyway, i created a utility file in utils/firebase.js
In the file, i have this function which gets all the paths in my collection and return an array of all documents found :
export const fetchPaths = () => {
let pathsRef = db.collection('paths');
let pathsArray = []
pathsRef.get().then((response) => {
response.docs.forEach(path => {
const {nom, coordonnees } = path.data();
pathsArray.push({ nom: nom, coordonnees: coordonnees})
})
console.log(pathsArray)
return pathsArray;
});
};
In my react component, What i want to do is to load this function in useEffect to have all the data, and then display them. Here is the code I use :
import { addPath, fetchPaths } from './Utils/firebase';
//rest of the code
useEffect(() => {
let paths = fetchPaths()
setLoadedPaths(paths);
}, [loadedPaths])
//.......
The issue here is if I console log pathsArray in the function it's correct, but it never gets to the state.
When i console log paths in the component file, i get undefined.
I am quite new with react, i tried different things with await/async, etc. But I don't know what i am doing wrong here / what i misunderstand.
I know that because of my dependency, i would be supposed to have an infinite loop, but it's not even happening
Thank you for your help
Have a nice day
fetchPaths does not return any result. It should be:
export const fetchPaths = () => {
let pathsRef = db.collection('paths');
let pathsArray = []
return pathsRef.get().then((response) => {
response.docs.forEach(path => {
const {nom, coordonnees } = path.data();
pathsArray.push({ nom: nom, coordonnees: coordonnees})
})
console.log(pathsArray)
return pathsArray;
});
};
note the return statement.
Since the fetchPaths returns a promise, in the effect it should be like following:
useEffect(() => {
fetchPaths().then(paths =>
setLoadedPaths(paths));
}, [loadedPaths])

Resources