0

Need to store and access values on an array in react. So far I found solutions that uses filters or does not fit my requirements.

Just need to push a string value with string key, and retrieve it with same key. How to do it?

Code:

import "./styles.css";
import { useRef } from "react";

export default function App() {
  const Presence = useRef({});

  function objTest() {
    Presence.current.length = 0;
    const uid = "UID1"; //Date.now().toString();

    //let obj = { [uid]:{ presence: "Busy"} };
    let obj = { [uid]: "Busy" };

    Presence.current.push(obj);

    console.log(Presence.current, " , ", Presence.current[uid]);
  }

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>

      {objTest()}
    </div>
  );
}
2
  • you mentioned array, but your code is using object. do u want object or array? You cannot access "busy" if you are using Presence.current[uid]. Commented May 8, 2021 at 10:54
  • I'm not sure which is possible for this need, my priority is object. Commented May 8, 2021 at 11:06

2 Answers 2

1

Just need to push a string value with string key, and retrieve it with same key

All modern browsers support map, which does exactly what you want:

const Presence = useRef(new Map());

You can use it like:

Presence.current.set(key, value)
Presence.current.has(key)
Presence.current.get(key)

Old way would be use an object literal like you have const Presence = useRef({}); and do use Property_accessors#bracket_notation like Presence.current[uid] = "Busy" to add dynamic keys. Object literals don't have a length or size property and are harder to enumerate so I don't recommend it unless you need to support IE

Sign up to request clarification or add additional context in comments.

6 Comments

Thank you for your response. Is there any other way without map?
Another way is to use an object literal like you have const Presence = useRef({}); and do Presence.current[uid] = "Busy". Object literals don't have a length or size property and are harder to enumerate so I don't recommend it unless you need to support IE
The code works fine on codesandBox, but on my project on VSCode it is giving me an error - TypeError: Presence.current.set is not a function . Will you please give me any hint on solving this?
@Rifat try console.log(Presence.current) and see if it's still a map. Maybe your actual cod is setting it to null or something at some point
Its resolved. One more thing that I need a way to update UI if the map value is changed. So I set another variable with useState const presenceCondition = useRef(new Map()); const [Presence, setPresence] = useState(new Map()); presenceCondition.current.set(uid, presenceConditionVariable); setPresence(presenceCondition.current); and updating and using its value, it initially shows but I'm not getting success on updating UI. Will you please help me to update UI?
|
1

Why not use state?

const Component = () => {

 const [ state, setState ] = useState({});
 const [ arrayState, setArrayState ] = useState([])
 const [ savedUid, setSavedUid ] = useState('') //need to save your UID too

 function objTest() {
    
        const uid = "UID1"; //Date.now().toString();
        setState({ [uid]: 'Busy'}) // object
        setArrayState(prev => [...prev, { [uid]: 'Busy' }] ) //array of objects
        setSavedUid(uid) //save your uid
 }
 console.log('Object', state[savedUid])
 console.log('Array of Objects', arrayState[0][savedUid])

 return <button onClick={objTest}>Click Me</button>

}

1 Comment

any way to retrieve value from arrayState without index or search ? arrayState[0][savedUid]?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.