-5

, I got the problem with useState on my ImageSlider. It doesn't update and I have no idea how to fix it. I tried everything and cleaned out the code. My friend also checked my code and nothing. I consoled it and it show just sticking to second image. I am learning so please excuse me if my mistake is very basic.

import React, {
  useState,
  useEffect
} from 'react';
import text from './ImageSliderText'

function ImageSlider() {

  const [choosen, setChoosen] = useState('')

  const changeHandler = () => {
    console.log(choosen)
    if (text.ImageSliderText[0].logo === choosen) {
      document.getElementById('imageSParagraph').innerHTML = text.ImageSliderText[1].paragraph;
      document.getElementById('imageSHeader').innerHTML = text.ImageSliderText[1].header;
      setChoosen(text.ImageSliderText[1].logo);
    } else if (text.ImageSliderText[1].logo === choosen) {
      document.getElementById('imageSParagraph').innerHTML = text.ImageSliderText[2].paragraph;
      document.getElementById('imageSHeader').innerHTML = text.ImageSliderText[2].header;
      setChoosen(text.ImageSliderText[2].logo);
      console.log('after', choosen)
    } else if (text.ImageSliderText[2].logo === choosen) {
      document.getElementById('imageSParagraph').innerHTML = text.ImageSliderText[3].paragraph;
      document.getElementById('imageSHeader').innerHTML = text.ImageSliderText[3].header;
      setChoosen(text.ImageSliderText[3].logo);
    } else if (text.ImageSliderText[3].logo === choosen) {
      document.getElementById('imageSParagraph').innerHTML = text.ImageSliderText[4].paragraph;
      document.getElementById('imageSHeader').innerHTML = text.ImageSliderText[4].header;
      setChoosen(text.ImageSliderText[4].logo);
    } else {
      document.getElementById('imageSParagraph').innerHTML = text.ImageSliderText[0].paragraph;
      document.getElementById('imageSHeader').innerHTML = text.ImageSliderText[0].header;
      setChoosen(text.ImageSliderText[0].logo);
    }
    setTimeout(() => changeHandler(), 4000)
  }
  useEffect(() => {
    setChoosen('tak')
    setTimeout(() => console.log('hehe', choosen), 4000)
    // changeHandler()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  return ( <
    div className = 'imageSlider' >
    <
    div className = 'imageSlider__textContainer' >
    <
    div className = 'imageSlider__textbox' >
    <
    p id = 'imageSParagraph'
    className = 'imageSlider__textbox--paragraph' > {
      text.ImageSliderText[0].paragraph
    } < /p> <
    p id = 'imageSHeader'
    className = 'imageSlider__textbox--header' > {
      text.ImageSliderText[0].header
    } < /p> <
    /div> <
    /div> <
    div className = 'imageSlider__logoContainer' > {
      text.ImageSliderText.map((element, index) => {
        return ( <
          div className = 'imageSlider__imagebox'
          key = {
            index
          } >
          <
          img style = {
            {
              opacity: choosen === element.logo ? '1' : '0.3'
            }
          }
          src = {
            element.logo
          }
          alt = 'logo'
          className = 'imageSlider__imagebox--image' / >
          <
          /div>
        )
      })
    } <
    /div>               <
    /div>
  )
}

export default ImageSlider

Here is other file with text.

import logo1 from '../../Images/dun.png'
import logo2 from '../../Images/frog.png'
import logo3 from '../../Images/green.png'
import logo4 from '../../Images/story.png'

export default {
  ImageSliderText: [{
      logo: logo1,
      paragraph: '"Uneasy barton seeing remark happen his has. Am possible offering at contempt mr distance stronger an. Attachment excellence announcing or reasonable am on if indulgence. Exeter talked in agreed spirit no he unable do.  "',
      header: 'Olivia Malerse, Dun Dunder'
    },
    {
      logo: logo2,
      paragraph: '"Greatest properly off ham exercise all. Unsatiable invitation its possession nor off. All difficulty estimating unreserved increasing the solicitude."',
      header: 'Joseph Redmaye'
    },
    {
      logo: logo3,
      paragraph: '"Among ready to which up. Attacks smiling and may out assured moments man nothing outward. Thrown any behind afford either the set depend one temper."',
      header: 'Meda Watson'
    },
    {
      logo: logo4,
      paragraph: '"And can event rapid any shall woman green. Hope they dear who its bred. Sm iling nothing affixed he carried it clothes calling he no."',
      header: 'Daniel Quentin'
    }
  ]
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
pushai
  • 1
  • 1
  • 1
    Does this answer your question? [useState set method not reflecting change immediately](https://stackoverflow.com/questions/54069253/usestate-set-method-not-reflecting-change-immediately) – Emile Bergeron May 29 '20 at 16:57

1 Answers1

0

So we have a little bit of work to do on this. First I will give you the fixed code and then lets talk about what you can do better.

function ImageSlider() {
  const [choosen, setChoosen] = useState("");

  const changeHandler = () => {    
    if (text.ImageSliderText[0].logo === choosen) {
      document.getElementById("imageSParagraph").innerHTML =
        text.ImageSliderText[1].paragraph;
      document.getElementById("imageSHeader").innerHTML =
        text.ImageSliderText[1].header;
      setChoosen(text.ImageSliderText[1].logo);
    } else if (text.ImageSliderText[1].logo === choosen) {
      document.getElementById("imageSParagraph").innerHTML =
        text.ImageSliderText[2].paragraph;
      document.getElementById("imageSHeader").innerHTML =
        text.ImageSliderText[2].header;
      setChoosen(text.ImageSliderText[2].logo);
    } else if (text.ImageSliderText[2].logo === choosen) {
      document.getElementById("imageSParagraph").innerHTML =
        text.ImageSliderText[3].paragraph;
      document.getElementById("imageSHeader").innerHTML =
        text.ImageSliderText[3].header;
      setChoosen(text.ImageSliderText[3].logo);
    } else if (text.ImageSliderText[3].logo === choosen) {
      document.getElementById("imageSParagraph").innerHTML =
        text.ImageSliderText[0].paragraph;
      document.getElementById("imageSHeader").innerHTML =
        text.ImageSliderText[0].header;
      setChoosen(text.ImageSliderText[0].logo);
    } else {
      console.log("in here");
      document.getElementById("imageSParagraph").innerHTML =
        text.ImageSliderText[0].paragraph;
      document.getElementById("imageSHeader").innerHTML =
        text.ImageSliderText[0].header;
      setChoosen(text.ImageSliderText[0].logo);
    }
  };
  useEffect(() => {
    setTimeout(() => changeHandler(), 4000);
    console.log("hehe", choosen);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [choosen]);

Issues:

1.) Your useEffect is only running once. That is what the [] means. The square brackets is where you put variables in that you want to monitor, then when they change, rerun this effect. So in the updated code, I have put choosen(should be spelt chosen, but call it anything you like) in there as that is what we are updating. This way, it will rerun the code everytime you setChoosen. So we are going to take the setChoosen out of your useEffect as you are setting it somewhere else.

2.) You only have 4 items in your array. Trying to access [4] is going to access the 5th element in your away which will blow up...You should be using index's based on the current length of your data.

3.) You aren't thinking in react. React is all about building reusable components. Here is an example of how I would rebuild your slider.

Recommendations:

  1. Read Think in react: https://reactjs.org/docs/thinking-in-react.html

  2. Get an account on https://codesandbox.io/ or other playground where you can type code and send it to people to ask for help.

  3. Keep Practicing
  4. Here is an example for you I put together showing you once you take the time to build out components, how you can easily reuse them to create/modify the rotator you are building: https://codesandbox.io/s/eloquent-pike-xklcj?file=/src/App.js
Sir Codes Alot
  • 1,149
  • 8
  • 11