0

this sounds like a dumb question but.. I'm starting in JS/MySQL and I'm using a front-end reactJS and back-end nodeJS. I'm trying to make a select form using the values from a table in MySQL database. This should be possible right?

here's my code (using a react component, semantic-ui forms)

class FormulaireCreerCollection extends Component {

  constructor() {
    super();

    this.state = {
      categories: []
    }
  }

  async componentDidMount() {
    const response = await fetch('http://localhost:3004/getCategories');
    const newList = await response.json();
    this.setState(previousState => ({
      ...previousState,
      categories: newList,
    }));
  }

  createOptions() {
    return this.state.categories.map((categorie, index) => <option key={index} value={index}>{categorie}</option>);

  }

  state = {}

  handleChange = (e, { value }) => this.setState({ value })

  render() { 
    const { value } = this.state
    return (
      <Form>
        <Form.Group widths='equal'>
          <Form.Field id='categories' fluid label='Catégories' control='select'>
              {this.createOptions()}
          </Form.Field>
          <Form.Input id='objet'fluid label="Nom de l'objet" placeholder="Nom de l'objet"  />
          <Form.Input id='image' fluid label="Image de l'objet" placeholder="Image de l'objet"  />

        </Form.Group>

        <Form.TextArea id='descObj' label="Description de l'objet" placeholder="Dites-en nous plus sur l'objet.." />
        <Form.Button onClick={this.handleClick}>Ajouter l'objet à la collection</Form.Button>

      </Form>
    )
  }
}

export default FormulaireCreerCollection;

What I would like to do is for example option {first value from table} then option {second value from table} etc..

This sounds really dumb but I haven't found my answer yet. Can anyone help me ?

Here's my json ouput:

[{"nom_categorie":"Alimentation"},{"nom_categorie":"Autres"},{"nom_categorie":"Cartes"},{"nom_categorie":"CD / DVD"},{"nom_categorie":"Consoles"},{"nom_categorie":"Images"},{"nom_categorie":"Informatique"},{"nom_categorie":"Jeux Vidéos"},{"nom_categorie":"Livres"},{"nom_categorie":"Moyens de locomotion"},{"nom_categorie":"Outillage"},{"nom_categorie":"Son"},{"nom_categorie":"Vêtements"}]

2 Answers 2

1

I have shown some basic ideas below. Adapt into your own use.
(Also, I believe you are using Express and mysql.js in the backend)

// in React
class WhatEver {
  constructor() {
    this.state = {
      categories: []
    }
  }
  
  componentDidMount() {
    // do AJAX call here
    someAjaxCall(..., (results) => {
      // This only shows the idea, do your own result processing instead and then setState
      this.setState({
        categories: results
      }) // triggers rerender
    })
  }
  
  createOptions = () => {
    return this.state.categories.map((e) => <option value={e} key={/* some unique key */}>{/* some name */}</option>)
  }
  
  render() {
    return (
      <Form.Field id='categories' fluid label='Catégories' control='select'>
        {this.createOptions() /* spread array elements in this way */}          
      </Form.Field>
    )
  }
}

Sign up to request clarification or add additional context in comments.

Comments

0

I'm trying to make a select form using the values from a table in MySQL database. This should be possible right?

Yes this is very possible.

You have most of the pieces you need to make it work but the thing you're missing is the network request from the client (i.e. the browser + react code) to your server (i.e. node + express).


your server code is completely fine as is:

app.get('/getCategories', function (req, res) {
    connection.query('SELECT nom_categorie FROM categories', function (error, results) {
      if (error) throw error;
     res.json(results);
  });
});

You should test to see if this works by calling your endpoint in your browser (e.g. http://localhost:8080/getCategories). You should see plain JSON in your browser. If you don't, troubleshoot why. If this doesn't work then your app won't load data.


Your client code is where you're missing the call to the server to get that data (remember, there are two parts to a full stack web application).

I would do something like this:

import * as React from 'react';

// you need a stateful component somewhere to fetch and update your data in app.
class MyForm extends React.Component {
  constructor() {
    super({});

    // give your component a default state
    this.state = {
      items: [],
    };
  }

  // use the componentDidMount hook to run as soon as the component is mounted to the DOM
  async componentDidMount() {
    // use the fetch API to make the call from client to server
    const response = await fetch('/getCategories');
    const newList = await response.json();
    this.setState(previousState => ({
      ...previousState,
      list: newList,
    }));
  }

  render() {
    return <Form.Field id='categories' fluid label='Catégories' control='select'>
      {this.state.items.map(obj => obj.nom_categorie).map((item, index) => <option
        key={index}
        value={index}
      >{item}</option>)}           
    </Form.Field>;
  }
}

So the strategy is:

  1. ensure your endpoint works by testing in your browser
  2. create a stateful react component with an initial state with an empty array
  3. create a render function that uses this.state.items to map the items array to react DOM nodes
  4. use the componentDidMount lifecycle hook to call your service using the fetch API and update the state of the component when it finishes.

Hopefully that helps. Good luck!

7 Comments

hey man! Thanks alot for your help I think i'm on the correct way to make this work! I've edited the original post with my code right now, (I've also used Kevin Qian's answer which helps me understand), but I get the error "Objects are not valid as a React child (found: object with keys {nom_categorie}). If you meant to render a collection of children, use an array instead." I'm guessing that's because it expects an array and not a json file ?
@Mich update your answer with the JSON outputted from your server
Sorry but what do you mean with updating the answer? I've tried multiple ways to do it, but I still get the same error =/. I've edited my original post so you can see my code atm
@Mich oh I meant update your question lol. add the Json output to your question so I can see the schema of the web service
@Mich, you were mapping to an object instead of a string. I updated my answer to add an additional map that maps the object {nom_categorie: 'value'} to simply 'value'. you got your types wrong is all
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.