0

I have this function in the back-end of my MERN (with M not for Mongo but MySQL) application. This function fetches all stocks in the database asynchronously and returns it as a callback.

getAllStocks: function(callback) {
    var context = dbContext.create();

    // First select the stock to get its price
    context.query(`SELECT  * from Stock`, function(err, result) {
        if (err) throw err;

        module.exports.stocks = callback(err, result);

    });

    return result;

}

I have tried to export the callback in a variable in this line:

module.exports.stocks = callback(err, result);

And to call it in my React App

import { stocks } from '../../Backend/StockFunctions';
import mysql from 'mysql';
import './App.css';

import React, { Component } from 'react'

export default class App extends Component {

constructor() {
  super();
  this.state = {
    stocks: []
  }
}

async componentDidMount() {
  console.log(stocks);
}

I have tried it this way and it prints an empty array.

I have also tried changing the function to this:

getAllStocks: function(callback) {
    var context = dbContext.create();

    // First select the stock to get its price
    context.query(`SELECT  * from Stock`, function(err, result) {
        if (err) throw err;

        callback(result);

        // Make sure that the user has enough of the stock to sell it (amout <= total stock qty)

    });
}

and calling it like this:

async componentDidMount() {
  getAllStocks(function(result) {
    return result;
  }) 
}

And then this is the error it returns:

error

How should I be doing this?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Randy Quackers
  • 665
  • 1
  • 7
  • 16

0 Answers0