0

I have initialized an array outside the useEffect and then performed certain operations on the array in the useEffect. When i print the array inside the useEffect I am getting correct values but if I print the same array ouside useEffect I am getting an empty array as the result.

The useEffect runs whenever there is a change in "values" array present in useState.

import Menu from './data';
const App = () => {
const [values, setvalues] = useState([]);
  const [ids, setids] = useState([]);
  let arrIds = [];
  let arrValue = [];
  var n = values.length;
  useEffect(() => {
    console.log("useEffect", values); //output: ["Frontend"]
    arrValue = [];
    Menu.filter(x => {
      if(values.includes(x.role)) {
        arrValue.push(x.id);
      }
      if(values.includes(x.level)) {
        arrValue.push(x.id);
      }
      if(x.languages.length > 0) {
        for(var i=0;i<n;i++) {
          if(x.languages.includes(values[i])) {
            arrValue.push(x.id);
          }
        }
      }
      if(x.tools.length > 0) {
        for(var i=0;i<n;i++) {
          if(x.tools.includes(values[i])) {
            arrValue.push(x.id);
          }
        }
      }
    });
    console.log("new array of id", arrValue); // output: [1, 3, 4, 7, 8, 10]
    arrValue = [...new Set(arrValue)];
    console.log("new array of id without repetition", arrValue); // output: [1, 3, 4, 7, 8, 10]
    if(arrValue) {
      arrIds.push(...arrValue);
      for(var a = 0;a<arrValue.length;a++) {
        var at = arrValue[a]
        console.log('arr val',at)
        setids(ids => [...ids, at]); 
      }
      console.log("setids ", ids);// output:[](not able to store the value of "at" in "ids" useState Array
      console.log("arrIds", arrIds);// output: [1, 3, 4, 7, 8, 10]
    }
  }, [values]);
console.log("arrIds", arrIds);// output:[] (empty array recieved outside the useEffect)
}

The data.js file contains array of objects:

export default [
  {
    "id": 1,
    "company": "Photosnap",
    "logo": Photosnap,
    "new1": true,
    "featured": true,
    "position": "Senior Frontend Developer",
    "role": "Frontend",
    "level": "Senior",
    "postedAt": "1d ago",
    "contract": "Full Time",
    "location": "USA Only",
    "languages": ["HTML", "CSS", "JavaScript"],
    "tools": []
  },
  {
    "id": 2,
    "company": "Manage",
    "logo": manage,
    "new1": true,
    "featured": true,
    "position": "Fullstack Developer",
    "role": "Fullstack",
    "level": "Midweight",
    "postedAt": "1d ago",
    "contract": "Part Time",
    "location": "Remote",
    "languages": ["Python"],
    "tools": ["React"]
  },
  {
    "id": 3,
    "company": "Account",
    "logo": account,
    "new1": true,
    "featured": false,
    "position": "Junior Frontend Developer",
    "role": "Frontend",
    "level": "Junior",
    "postedAt": "2d ago",
    "contract": "Part Time",
    "location": "USA Only",
    "languages": ["JavaScript"],
    "tools": ["React", "Sass"]
  },
  {
    "id": 4,
    "company": "MyHome",
    "logo": myhome,
    "new1": false,
    "featured": false,
    "position": "Junior Frontend Developer",
    "role": "Frontend",
    "level": "Junior",
    "postedAt": "5d ago",
    "contract": "Contract",
    "location": "USA Only",
    "languages": ["CSS", "JavaScript"],
    "tools": []
  },
  {
    "id": 5,
    "company": "Loop Studios",
    "logo": loopstudios,
    "new1": false,
    "featured": false,
    "position": "Software Engineer",
    "role": "FullStack",
    "level": "Midweight",
    "postedAt": "1w ago",
    "contract": "Full Time",
    "location": "Worldwide",
    "languages": ["JavaScript"],
    "tools": ["Ruby", "Sass"]
  },
  {
    "id": 6,
    "company": "FaceIt",
    "logo": faceit,
    "new1": false,
    "featured": false,
    "position": "Junior Backend Developer",
    "role": "Backend",
    "level": "Junior",
    "postedAt": "2w ago",
    "contract": "Full Time",
    "location": "UK Only",
    "languages": ["Ruby"],
    "tools": ["RoR"]
  },
  {
    "id": 7,
    "company": "Shortly",
    "logo": shortly,
    "new1": false,
    "featured": false,
    "position": "Junior Developer",
    "role": "Frontend",
    "level": "Junior",
    "postedAt": "2w ago",
    "contract": "Full Time",
    "location": "Worldwide",
    "languages": ["HTML", "JavaScript"],
    "tools": ["Sass"]
  },
  {
    "id": 8,
    "company": "Insure",
    "logo": insure,
    "new1": false,
    "featured": false,
    "position": "Junior Frontend Developer",
    "role": "Frontend",
    "level": "Junior",
    "postedAt": "2w ago",
    "contract": "Full Time",
    "location": "USA Only",
    "languages": ["JavaScript"],
    "tools": ["Vue", "Sass"]
  },
  {
    "id": 9,
    "company": "Eyecam Co.",
    "logo": eyecamco,
    "new1": false,
    "featured": false,
    "position": "Full Stack Engineer",
    "role": "Fullstack",
    "level": "Midweight",
    "postedAt": "3w ago",
    "contract": "Full Time",
    "location": "Worldwide",
    "languages": ["JavaScript", "Python"],
    "tools": ["Django"]
  },
  {
    "id": 10,
    "company": "The Air Filter Company",
    "logo": the,
    "new1": false,
    "featured": false,
    "position": "Front-end Dev",
    "role": "Frontend",
    "level": "Junior",
    "postedAt": "1mo ago",
    "contract": "Part Time",
    "location": "Worldwide",
    "languages": ["JavaScript"],
    "tools": ["React", "Sass"]
  }
]

Should I try storing the values in a useState array instead of normal array, if YES, How?

PLEASE HELP ME FIX THIS CODE, Thank you.

Angelin
  • 95
  • 1
  • 9

1 Answers1

0

You should make arrIds part of the component state.

const App = () => {
  const [values, setvalues] = useState([]);
  const [ids, setids] = useState([]);

  const [arrIds, setArrIds] = useState([]); // <-- create arrIds state array

  ...

  useEffect(() => {
    arrValue = [];
    Menu.filter((x) => {
      ...
    });
    arrValue = [...new Set(arrValue)];

    if (arrValue) {

      setArrIds(arrIds => [...arrIds, ...arrValue]); // <-- shallow copy & append

      for (var a = 0; a < arrValue.length; a++) {
        ...
      }
    }
  }, [values]);
};
Drew Reese
  • 165,259
  • 14
  • 153
  • 181
  • Hi @Angelin Has this answered sufficiently resolved your question/issue? – Drew Reese Apr 24 '21 at 07:38
  • hi, I am getting a different value inside the useEffect and different outside the useEffect. `const [arrIds, setArrIds] = useState([]); // <-- create arrIds state array ... arrValue = []; ... arrValue = [...new Set(arrValue)]; //output: [1,3,4,5] if (arrValue) { setArrIds(arrIds => [...arrIds, ...arrValue]); console.log("arrIds ", arrIds); //output: [1,4,5] }, [values]); console.log("arrIds ", arrIds); //output: [1,3,4,5] };` – Angelin Apr 24 '21 at 10:17
  • can you please help me with this? Why am i getting value less inside the useEffect? – Angelin Apr 24 '21 at 10:23
  • @Angelin If you are attempting to console log state you ***just*** enqueued an update for it will only log the state from the ***current*** render cycle you are still in. React state updates are asynchronously processed. If you want to log state updates then please use an `useEffect` hook with a dependency on the state you want to log updates of. See [useState method not reflecting change immediately](https://stackoverflow.com/questions/54069253/usestate-set-method-not-reflecting-change-immediately). – Drew Reese Apr 24 '21 at 18:25
  • If i add `arrIds` to my useEffect depedencies, I am not able to open my console at all, cause errors are poping up every second when i add `arrIds` to my useEffect depedencies. – Angelin Apr 25 '21 at 05:10
  • @Angelin You know you can use more than one `useEffect` hook, right? Sorry if it wasn't clear, but to log the state update you would use a separate effect hook just for that purpose. – Drew Reese Apr 25 '21 at 05:35