Gjermund Wiggen
Gjermund Wiggen

Reputation: 95

Updating a variable in return() in react-native

I am fairly new to React and React-native and I'm struggling to understand how I am supposed to update a variable in the return method.

Currently this is my code

import React, { Component } from "react";
import { View, StyleSheet, Platform, Text, Button } from "react-native";

export default class App extends Component<{}> {
  constructor() {
    super();
    this.handleClick = this.handleClick.bind(this);
  }
  handleClick = test => {
    fetch("http://192.168.1.237:3000/thoughts")
      .then(res => res.json())
      .then(res => {
        return (test = JSON.stringify(res));
        return JSON.stringify(res);
      })
      .catch(error => {
        console.error(error);
      });
  };
  componentDidMount() {}

  render() {
    var test = 12314214;

    return (
      <View style={[styles.container]}>
        <Text style={styles.text}>{test}</Text>
        <Button
          onPress={this.handleClick.bind(this)}
          title="Learn More"
          color="#841584"
        />
      </View>
    );
  }
}

What I'm trying to do is to get "{ test }" updated when I click the button. The button works and if I console.log the button the test variable is updated. I'm guessing there's something fundamental missing here. Any help appreciated.

Upvotes: 3

Views: 16328

Answers (3)

Luhaib-j
Luhaib-j

Reputation: 99

You can use react useState() hook to update the value of any variable and you can use the new destructuring functionality of js.

const Component = () => {
   var [state, setState] = usestate("old value")
   changeState = () => {
    return setstate(state = "new value")
   }
   return (
   <>
   <p>{state}</p>
   <button onclick={changeState}>change</button>
   </>
  )
}

Upvotes: 2

dvvtms
dvvtms

Reputation: 627

your doing it wrong... one way for update react components is use setState: https://reactjs.org/docs/react-component.html#setstate

test = 12314214;

class App extends Component {
  state = { test }
  constructor() {
    super();
    this.handleClick = this.handleClick.bind(this);
  }
  handleClick = event => {
    fetch("http://192.168.1.237:3000/thoughts")
      .then(res => res.json())
      .then(res => {
        // return (test = JSON.stringify(res));
        test = JSON.stringify(res);
        this.setState({ test })
        return test;
      })
      .catch(error => {
        console.error(error);
      });
  };
  componentDidMount() { }

  render() {
    // var test = 12314214;
    const { test } = this.state
    return (
      <View style={[styles.container]}>
        <Text style={styles.text}>{test}</Text>
        <Button
          onPress={this.handleClick.bind(this)}
          title="Learn More"
          color="#841584"
        />
      </View>
    );
  }
}

Upvotes: 0

Joe Lloyd
Joe Lloyd

Reputation: 22483

Your scope is incorrect and you should use this.setState to cause a rerender

Instead of having a var contain a value use

this.state = {test: '124'}

In the constructor

Then use

this.setState({test: value_returned_from_fetch })

Inside the .then from your fetch

At the return level inside the component print this.state.test

State explanation

So inside a react component you have a local state object in this.state it can be set in the constructor like this.state = {bar: 'foo'};. After the constructor has set the state it should only be changed with the this.setState() method.

Upon changing the state with setState the component will re-render with the updated values.

The state is not available outside of the component, at least not available as this.state because that would call the local state of the current component.

If you need to use a value from the state of a parent component you can pass it to a child. At that point it becomes a prop of the child accessible with this.props

To change the value of state from a child component you should pass a function to the child that changes the state of the parent.

This process of passing state changing functions becomes increasingly complex as your app grows, I would suggest using a library like Redux to manage app state via actions and reducers. There is a steep learning curve but once you have a grasp of this modified flux methodology you will wonder how you ever lived without it.

Upvotes: 4

Related Questions