So this is an example of the problem I am having.
import { useState, useEffect } from "react";
import symbols from "./Symbols.js"
const DrawSymbol = (type) => {
const [state, setState] = useState("");
useEffect(() => {
const g = symbols.find((obj) => {
return obj[type];
});
setState(g.url);
},[]);
return <div>{state}<div>
};
Symbol.js has svg data so Ill just truncate it for legibility
const symbols = [
{
"0":{
"url":"data:image/svg+xml;base64,PHN2ZyB4bWxucz..."
}
},
{
"1":{
"url":"data:image/svg+xml;base64,PHN2ZyB4bWxucz0naHR0cD....."
}
},
{
"2":{
"url":"data:image/svg+xml;base64,PHN2ZyB4bWxucz0naHR0cDov..= "
}
},
{
"2B":{
"url":"data:image/svg+xml;base64,PHN2ZyB4bWxucz0naHR0c.... "
}
},
.....
]
export default symbols;
Symbols.js exports an array of objects to this file. The issue here is that if I were to manual say obj['name'] it works and it returns the requested object but if I try to use the passed variable name obj[type] it comes up as undefined. Using the debugger in Firefox I can see that the variable being passed does indeed have a String value, but it still never works. Its driving really mad.
const DrawSymbol = (props) => {
const [state, setState] = useState("");
useEffect(() => {
if(props.type) {
// `symbols` is a array of object. you need to find one object from that array
const g = symbols.find((obj) => obj.type === props.type);
setState(g?.text);
}
}, [props]);
return <div>{state}<div>
};
Try this out.
I don't exactly know what you are up to without actually seeing your Symbol.js file. But a quick glance probably shows that shouldn't you be destructuring the type like const DrawSymbol = ({type}) => { ... rest of the code } if you are passing the type as props into this component.? If not then you are actually using the find method incorrectly. Find method finds the first element it matches according to the condition given. Here you actually are directly returning which would obviously return false since you are not giving any condition using which it would find it inside the array.
The correct way would be -
useEffect(() => {
if(type) {
const g = symbols.find((obj) => obj.type === type);
setState(g.text);
}
}, [type]);
Here in the above code it would return exactly the thing you need since here we are giving the condition using which it would match it inside the array.
You can solve this with useMemo:
import { useMemo } from "react";
import symbols from "./Symbols.js";
const DrawSymbol = ({type}) => {
const symbolText = useMemo(() => symbols.find(s => s.type === type)?.text ?? '', [type]);
return <div>{symbolText}<div>;
};