b0bgetout
b0bgetout

Reputation: 25

Problem with operating a data from express

im new to the express and react Trying to make my first app but i have a problem with operating on my data from express. Express

const express = require('express');
const bodyParser = require('body-parser');

const app = express();
const port = process.env.PORT || 5000;

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.get('/favcolors', (req, res) => {
    const colors = [
        'red',
        'green',
        'yellow'
    ];
    res.json(colors);
});

app.listen(port, () => console.log(`Listening on port ${port}`));

React

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { 
      colors: []
    }
  }
  callApi = async () => {
    const response = await fetch('/favcolors');
    const body = await response.json();
    if (response.status !== 200) throw Error(body.message);

    return body;
};
  componentDidMount() {
  this.callApi()
  .then(colors => this.setState({colors}, () => console.log('Fetch data ', colors)));
  console.log(this.state.data)
}
wantYellow = () => {
  this.setState({});
};
  render() {
    return (
      <div>
        <h1>
          Fav colors: {this.state.colors[0]}
        </h1>
        <button type="button" onClick={this.wantYellow}>
          Change
        </button>
      </div>
    );
  }
}
export default App;

I want to change "Fav Color " from red - this.state.colors, to yellow using a button but i dont know how to do it. Can you give me some examples?

Upvotes: 0

Views: 21

Answers (1)

Muhammad Zeeshan
Muhammad Zeeshan

Reputation: 4748

One way of doing this is maintaining the index of colors in state like:

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { 
      colors: [],
      index: 0
    }
    this.wantYellow = this.wantYellow.bind(this);
  }
  callApi = async () => {
    const response = await fetch('/favcolors');
    const body = await response.json();
    if (response.status !== 200) throw Error(body.message);

    return body;
};
  componentDidMount() {
  this.callApi()
  .then(colors => this.setState({colors}, () => console.log('Fetch data ', colors)));
  console.log(this.state.data)
}
wantYellow = () => {
  this.setState({ index: 2 });
};
  render() {
    return (
      <div>
        <h1>
          Fav colors: {this.state.colors[this.state.index]}
        </h1>
        <button type="button" onClick={this.wantYellow}>
          Change
        </button>
      </div>
    );
  }
}
export default App;

Hope this will help you.

Upvotes: 1

Related Questions