blue
blue

Reputation: 7375

React native - 'undefined is not an object'?

Alright, going off this answer React native - "this.setState is not a function" trying to animate background color? Im just trying to loop fade the background color of a view in React Native.

export default props => {
  let [fontsLoaded] = useFonts({
    'Inter-SemiBoldItalic': 'https://rsms.me/inter/font-files/Inter-SemiBoldItalic.otf?v=3.12',
        'SequelSans-RomanDisp' : require('./assets/fonts/SequelSans-RomanDisp.ttf'),
        'SequelSans-BoldDisp' : require('./assets/fonts/SequelSans-BoldDisp.ttf'),
        'SequelSans-BlackDisp' : require('./assets/fonts/SequelSans-BlackDisp.ttf'),
  });


  //Set states and hooks
  //To change state 'color' - setColor('#ff0000');
  const colors = ["#fff", "#ff0000", "#00ff00", "#0000ff", "#0077ff"];
  const [color, setColor] = useState("#fff");
  const [backgroundColor, setBackgroundColor] = useState(new Animated.Value(0));
  const [time, setTime] = useState(0);
  //const t = colors[randNum(0, colors.length)];

  //random num, exclusive
  function randNum(min, max) {
    return Math.floor(min + Math.random() * (max - min));
  }

  useEffect(() => {
    setBackgroundColor(new Animated.Value(0));
  }, []); // this will be only called on initial mounting of component,
  // so you can change this as your requirement maybe move this in a function which will be called,
  // you can't directly call setState/useState in render otherwise it will go in a infinite loop.

  useEffect(() => {
    Animated.timing(backgroundColor, {
      toValue: 100,
      duration: 5000
    }).start();
  }, [backgroundColor]);

  var bgColor = this.state.color.interpolate({
    inputRange: [0, 300],
    outputRange: ["rgba(255, 0, 0, 1)", "rgba(0, 255, 0, 1)"]
  });

  useEffect(() => {
    const interval = setInterval(() => {
      //setTime(new Date().getMilliseconds());
      setColor("#ff0000");
    }, 36000);
    return () => clearInterval(interval);
  }, []);

With this, everything checks out except var bgColor = this.state.color which creates error

undefined is not an object evaluating ..

I dont understand why this is a problem since I set color to useState('#fff') I want to use color in my Stylesheet as backgroundColor.

How can I set this properly?

Upvotes: 0

Views: 700

Answers (3)

Hamza Murtaza
Hamza Murtaza

Reputation: 50

In functional components, you do not access the component's state properties/variables using this.state.abc, instead you just use the name of the state variable directly. So what you should do is:

    var bgColor = color.interpolate({
      inputRange: [0, 300],
      outputRange: ['rgba(255, 0, 0, 1)', 'rgba(0, 255, 0, 1)']
    });

Upvotes: 0

ESI
ESI

Reputation: 2047

If your component is a function you shouldn't use this.state., but you have to call directly to the state name.

In your code:

var bgColor = color.interpolate({...})

instead of:

var bgColor = this.state.color.interpolate({...})

From react DOCS

Reading State

When we want to display the current count in a class, we read this.state.count:

<p>You clicked {this.state.count} times</p>

In a function, we can use count directly:

<p>You clicked {count} times</p>

Upvotes: 1

Ashwith Saldanha
Ashwith Saldanha

Reputation: 1728

Here is an example don't create state for animated value instead use memo to initialise it once and update it using timing function

snack: https://snack.expo.io/GwJtJUJA0

code:

export default function App() {
  const { value } = React.useMemo(
    () => ({
      value: new Animated.Value(0),
    }),
    []
  );

  React.useEffect(() => {
    Animated.loop(
      Animated.sequence([
        Animated.timing(value, {
          toValue: 1,
          duration: 1000,
        }),
        Animated.timing(value, {
          toValue: 0,
          duration: 1000,
        })
      ])
    ).start();
  }, []);

  const backgroundColor = value.interpolate({
    inputRange: [0, 1],
    outputRange: ['#0dff4d', '#ff390d'],
  });

  return (
    <View style={styles.container}>
      <Animated.View style={{ width: 200, height: 100, backgroundColor }} />
    </View>
  );
}

Upvotes: 0

Related Questions