-4

Beginner here, I have a setTimeout configured something like this that parses json from session storage

  setTimeout(() => {
    const blog = JSON.parse(sessionStorage.blogs);
    console.log(blog);
  }, 1000)

all I want to do is use the blog const outside the timeout which would make things easier,

setTimeout(() => {
    const blog = JSON.parse(sessionStorage.blogs);
  }, 1000)    
console.log(blog); <------ this does not work

I get the Undefined error

'blog' is not defined  no-undef
  • 1
    Even if you define `blog` outside the arrow function the `console.log()` line will always run before the timeout completes. This definitely feels like an [XY Problem](https://xyproblem.info/) – Phil Jan 13 '22 at 03:09
  • 1
    Why are you reading from the session storage in a `setTimeout`? – Vektor Jan 13 '22 at 03:18

4 Answers4

0

If you need it outside, you'll need

  • to use state so you can set the state inside the timeout callback
  • to log it only when it gets initialized, and not on every render, use useEffect with it in the dependency array
const [blog, setBlog] = useState();
useEffect(() => {
  setTimeout(() => {
    setBlog(JSON.parse(sessionStorage.blogs));
  }, 1000);
}, []); // run only once, on mount
useEffect(() => {
  if (blog) { // only log once it exists
    console.log(blog);
  }
}, [blog]); // run only when the state changes
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
-1

I think you can use Promise to help you to fix this problem.

const [blog, setBlog] = useState()
new Promise((resolve) => {
  setTimeout(() => {
    const sessionBlog = JSON.parse(sessionStorage.blogs);
    resolve(sessionBlog);
  }, 1000)
}).then((res) => {
  console.log(res);
  setBlog(res);
})

useEffect(() => {
  console.log('blog has changed, you can do whatever you want here')
}, [blog])
-2

That's because setTimeout is async, your console.log will run first before the setTimeout (even if it is 0 seconds)..

jove0610
  • 664
  • 1
  • 8
  • 16
-4

How about this

let blog;
setTimeout(() => {
    blog = JSON.parse(sessionStorage.blogs);
  }, 1000)    
console.log(blog);
Ernesto
  • 3,944
  • 1
  • 14
  • 29