-2

I created a Json file, and is running ok, but it doesn't insert a new item, only delete is working. Below follows the code. I'm just simulating a server with some input, delete and update, I'm working with React 18.1.0 and Material-ui. The json data file "src/data/db.json" it loads properly from the component "Notes". I need to insert a new item on the function handleSubmit, which is on form onSubmit.

Function to insert a new item, and after, go to the root page "/".

export default function Bancos(){
    const classes = useStyles()
    const history = useHistory()
    const [name, setName] = useState('')
    const [address, setAddress] = useState('')
    const [nameError, setNameError] = useState(false)
    const [addressError, setAddressError] = useState(false)
    const [status, setStatus] =useState('active')

    const handleSubmit = (e) => {
        e.preventDefault()
        setNameError(false)
        setAddressError(false)

        if(name == ''){
            setNameError(true)
        }

        if(address == ''){
            setAddressError(true)
        }

        if( name && address){
            fetch('http://localhost:8000/banks', {
                method: 'POST',
                headers: { "Content-type": "application/json" },
                body: JSON.stringify({name, address, status})
                .then(() =>  history.push('/')),
            })
           
        }
        
    }

    return(
        <Container>
           <Typography  variant="h6" color="textSecondary" align="center" gutterBottom
            className="titleBank">
               Cadastrar um novo Banco
           </Typography>

            <form noValidate autoComplete="off" onSubmit={handleSubmit}>

 Deleting is working correctly. Why insert doesn't work?
 
 export default function Notes(){
    const [ notes, setNotes ] = useState([]); 

    useEffect(() => {
        fetch('http://localhost:8000/banks')
        .then(res => res.json())
        .then(data => setNotes(data))
    }, []);

const handleDelete = async (id) => {
    await fetch('http://localhost:8000/banks/' + id, {
        method: 'DELETE'
    })
    const newNotes = notes.filter(note => note.id != id) ;
    setNotes(newNotes);
}

    return(
        <Container>
            <Grid container spacing={3}>
           {notes.map(note => (
               <Grid item key={note.id} xs={12} md={6} lg={4}>
                  <CardBanks note={ note } handleDelete={handleDelete}/>  {/*passing props note with element note */}
               </Grid>
           ))}
           </Grid>
        </Container>
    )
}

Best regards and thanks in advance.

1 Answers1

-1

I solved this using this code: .then was placed inside the function, so it should be placed at the end of parenthesis, next line.

import React, { useState } from 'react';
import { FormControlLabel, RadioGroup, Typography } from '@mui/material';
import { Button } from '@mui/material';
import { Container } from '@mui/material';
import KeyboardArrowRightIcon from '@mui/icons-material/KeyboardArrowRight';
import { makeStyles } from '@mui/styles';
import { TextField } from '@mui/material';
import { Radio } from '@mui/material';
import { FormLabel } from '@mui/material';
import { FormControl } from '@mui/material';
import { useHistory } from 'react-router-dom';
import '../Styles.css';
import { Box } from '@mui/material';


const useStyles = makeStyles(({
    
    field: {
        spacing: 4,
        display: "block",
    }
    
}));

export default function Bancos(){
    const classes = useStyles()
    const history = useHistory()
    const [title, setTitle] = useState('')
    const [details, setDetails] = useState('')
    const [titleError, setTitleError] = useState(false)
    const [detailsError, setDetailsError] = useState(false)
    const [status, setStatus] =useState('active')

    const handleSubmit = (e) => {
        e.preventDefault()
        setTitleError(false)
        setDetailsError(false)

        if(title == ''){
            setTitleError(true)
        }

        if(details == ''){
            setDetailsError(true)
        }

        if( title && details){
            fetch('http://localhost:8000/notes', {
                method: 'POST',
                headers: { "Content-type": "application/json" },
                body: JSON.stringify({ title, details, status })
            })
            .then(() =>  history.push('/'))
        }
    }

    return(
        <Container>
           <Typography  variant="h6" color="textSecondary" align="center" gutterBottom
            className="titleBank">
               Cadastrar uma nova  Tarefa - Post-It
           </Typography>

            <form noValidate autoComplete="off" onSubmit={handleSubmit}>
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jun 02 '22 at 13:24