Home > Blockchain >  I am getting a map is not a function error in react js
I am getting a map is not a function error in react js

Time:11-06

I am trying to get data from mysql database using spring boot and react js and display it in a table formate but I am getting an error while displaying it

componentDidMount(){
        const currentUser = AuthService.getCurrentUser();
        let userId = {...this.state.userId};
        userId = currentUser.id;
        this.setState({userId});

        UserService.getExpense(userId).then((res) =>{
            this.setState({Expenses: res.data});
        });
    }
</thead>
                            <tbody>
                                {
                                    this.state.Expenses.map(
                                        (expense, key) => {
                                            return (
                                                <tr key = {key}>
                                                    <td> {expense.title} </td>   
                                                    <td><Moment date={expense.date} format="YYYY/MM/DD"/></td>
                                                    <td> {expense.category}</td>
                                                    <td> {expense.amount}</td>
                                                    <td>
                                                        <button onClick={ () => this.deleteExpense(expense.id)} className="btn btn-danger">Delete </button>
                                                    </td>
                                                </tr>
                                            )
                                        }
                                    )
                                }
                            </tbody>
                        </table>

here is the axios function

const API_URL_EX = 'http://localhost:8080/api/test/expense';

getExpense(userId){
    return axios.get(API_URL_EX   '/' userId);
  }

here is my spring boot controller

@GetMapping("/expense/{userId}")
    public ResponseEntity<?> getExpense(@PathVariable Long userId){
        Optional<Expense> expense = expenseRepository.findByUserId(userId);
        return expense.map(response -> ResponseEntity.ok().body(response))
                .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }

here is the data in database

# id, amount, category, date, title, user_id
'1', '50000', 'Shopping', '2022-11-06 11:21:23', 'Dubai Trip', '1'

The console log is show the following error

viewexpense.component.js:68 Uncaught TypeError: this.state.Expenses.map is not a function
    at ViewExpense.render (viewexpense.component.js:68:1)
    at finishClassComponent (react-dom.development.js:19752:1)
    at updateClassComponent (react-dom.development.js:19698:1)
    at beginWork (react-dom.development.js:21611:1)
    at HTMLUnknownElement.callCallback (react-dom.development.js:4164:1)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:4213:1)
    at invokeGuardedCallback (react-dom.development.js:4277:1)
    at beginWork$1 (react-dom.development.js:27451:1)
    at performUnitOfWork (react-dom.development.js:26557:1)
    at workLoopSync (react-dom.development.js:26466:1)

CodePudding user response:

Set default value to expense when initializing the state

    this.setState({userId, Expenses : []});

CodePudding user response:

Found it. There was a problem in my restcontroller changed it to

@GetMapping("/expense/{userId}")
    public ResponseEntity<List<Expense>> getExpense(@PathVariable Long userId){
        return new ResponseEntity<List<Expense>>(expenseRepository.findByUserId(userId), HttpStatus.OK);
    }
  • Related