Modal box fails to refresh content

Currently, I am in the process of learning how to modify my blog using a modal window. However, when I click on the edit button within the modal, an error message

'Failed to execute 'fetch' on 'Window': Invalid name'
appears in the console. The issue seems to be located within the following code snippet:

import React, { Fragment, useState } from "react";
import "bootstrap/dist/css/bootstrap.min.css";

const EditTodo = ( { blog }) => {

  const [title, setTitle] = useState(blog.title)
  const [content, setContent] = useState(blog.content)

  const editText = async (id) => {

    const body = {title, content}
    console.log(JSON.stringify(body))
    try {
      const res = await fetch(`http://localhost:5000/blog/${id}`, {
        method: "PUT",
        headers: {'Content Type': 'application/json'},
        body: JSON.stringify(body)
      })

      console.log(res)

    } catch (err) {
      console.error(err.message)
    }
  }

  return (
    <Fragment>
  <button type="button" className="btn btn-warning" data-toggle="modal" data-target={`#id${blog.post_id}`}>
    Edit
  </button>
  
  <div className="modal" id={`id${blog.post_id}`}>
    <div className="modal-dialog">
      <div className="modal-content">
        <div className="modal-header">
          <h4 className="modal-title">Edit Blog</h4>
          <button type="button" className="close" data-dismiss="modal">&times;</button>
        </div>
      
        <div className="modal-body">
          <input type='text' className='form-control' value={title} onChange={e => setTitle(e.target.value)}/>
          <input type='text' className='form-control' value={content} onChange={e => setContent(e.target.value)}/>
        </div>
      
        <div className="modal-footer">
          <button type="button" className="btn btn-warning" data-dismiss="modal" onClick={() => editText(blog.post_id)}>Edit</button>
          <button type="button" className="btn btn-danger" data-dismiss="modal">Close</button>
        </div>
     
      </div>
    </div>
  </div>
  </Fragment>
  )
}

export default EditTodo;

Though I have reviewed my fetch call and can't seem to find any mistakes, it appears that the error is occurring during this function:

const editText = async (id) => {

    const body = {title, content}
    console.log(JSON.stringify(body))
    try {
      const res = await fetch(`http://localhost:5000/blog/${id}`, {
        method: "PUT",
        headers: {'Content Type': 'application/json'},
        body: JSON.stringify(body)
      })

      console.log(res)

    } catch (err) {
      console.error(err.message)
    }
  }

Answer №1

I was able to reproduce the issue by entering the following command in the browser console

fetch('http://localhost:3000', {method: 'PUT', headers: {'Content Type': 'application/json'}, body: "{}"})

However, the error did not occur when I used this command:

fetch('http://localhost:3000', {method: 'PUT', headers: {'Content-Type': 'application/json'}, body: "{}"})

The root cause of the problem lies in the header name. It should be Content-Type instead of Content Type.

Answer №2

After making the change to axios.put, the error disappeared and I successfully updated my modal.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Reload React Page

I'm working on a function to update information in my database using React as the frontend. The issue I'm facing is that even though I can successfully update the item in the database, it doesn't reflect in real-time on the page unless I man ...

The attribute 'status' is not found in the 'ServerResponse' type (TS2339)

I've attempted to develop an interface and install React types, but the only way it seems to work is when I write the code in JavaScript. However, within a TypeScript project, I encounter this error: Property 'status' does not exist on typ ...

What is the process of transforming async/await code into synchronous code in JavaScript?

Blocking the event loop is generally considered bad practice due to its consequences. However, even the native fs module includes some synchronous functions for specific purposes, such as CLIs using fs.readFileSync. I am interested in converting the follo ...

Cease the execution of promises as soon as one promise is resolved

Using ES6 promises, I have created a function that iterates over an array of links to search for an image and stops once one is found. In the implementation of this function, the promise with the fastest resolution is executed while others continue to run ...

Determine if a key begins with a specific string within an object and retrieve the corresponding value

If I have an object like this: let fruitSong = {'apple song':12, 'banana song': 24} Object.keys(fruitSong).forEach(e=>{ if(e.startsWith('apple')){ console.log(fruitSong[e]) } }) Is there a different meth ...

"PHP and Javascript Validation Library: Building Confidence in Your Data

Looking for a PHP form validation library that can work independently outside of any PHP framework? It should be able to handle basic validations like checking for empty fields, using regex, validating email addresses, and alphanumeric characters. Ideally, ...

Is it possible to trigger a JavaScript function and an AJAX command with just one button click?

I'm looking to achieve a specific functionality using one button within a form. The requirements are as follows: 1) When the button is clicked, it should trigger a JavaScript function that performs animations such as fadeout and fadein. 2) Following ...

Steps for eliminating a button when the API no longer provides any information

Everything is functioning smoothly with the code below, but I would like to enhance it so that when I call getNextPers() and there is no information available, the Ver Mais button disappears. I have been researching solutions without success, so any assi ...

Tips for successfully including a forward slash in a URL query string

My query involves passing a URL in the following format: URL = canada/ontario/shop6 However, when I access this parameter from the query string, it only displays "canada" and discards the rest of the data after the first forward slash. Is there a way to ...

Relocate the form element from its current position inside the form, and insert it into a different div

I have a sidebar on my website with a search/filter form. I am attempting to relocate one of the elements (a sort order dropdown) from this form, outside the form using CSS/JS and display it inside a div on the right side. Is it possible to do this without ...

Why did my compilation process fail to include the style files despite compiling all other files successfully?

As English is not my first language, I kindly ask for your understanding with any typing mistakes. I have created a workspace with the image depicted here; Afterwards, I executed "tsc -p ." to compile my files; You can view the generated files here Unf ...

Output the word 'Days', 'Months', or 'Years' depending on the value of N, which represents the number of days

I am currently utilizing moment.js in conjunction with vue 3. I've implemented a function that calculates the disparity between two dates. The functionality works as expected, but here's where my query comes in. The function is structured like so ...

Is there a way to ensure uniform display of HTML form error messages across various browsers?

Recently, I completed a login form that consists of username and password fields. For the username, I used a text field with the type email, while for the password, I utilized a text field with the type password which requires validation through a regex pa ...

Seems like JavaScript's .active functionality is failing to function properly in my case

I'm encountering an issue with my website's homepage. I have a list of services displayed, and the intention is for a description to appear when one of the services is clicked. However, clicking on the buttons does not trigger the expected action ...

Browser inconsistencies result in varying appearance of Bootstrap selection in Firefox and Chrome

Issue with Bootstrap select rendering in Firefox and Chrome: Firefox: https://i.sstatic.net/HWEcR.png Chrome: https://i.sstatic.net/GBuDP.png Looking for ways to make the two browsers render consistently, preferably in Chrome's style. This questio ...

The Dojo claro css method utilizes absolute positioning for styling ContentPane elements

I am currently utilizing dojo 1.8 and facing an issue with unwanted padding in my bordercontainer/contentpane layout. The problem arises when I incorporate the claro css file, as it seems to apply styles directly inline to the div elements used for my cont ...

What is the best way to incorporate text transitions using jquery?

Recently, I've come across this code snippet: $('#slider_title').text(var); This line of code successfully adds the text stored in a variable to the paragraph identified by the id "slider_title". And now, my goal is to smoot ...

Any recommendations for building HTML in an iOS UIWebView?

When using a UIWeb view, how can I create HTML content? For example, I have some header html code. Then, I would like to include a JavaScript script and pass data to it. Once the JavaScript is injected, I want to add the remaining HTML content from a .html ...

The HTML video controls in Safari take precedence over the window.name attribute

When using Safari 8.0.5, the controls attribute for the video element will change the value of window.name to "webkitendfullscreen". This is significant because I rely on using window.name to store client-side data in Safari's private mode, where loca ...

Preventing overlapping of a "position-fixed" element with variable size: Effective strategies

I am trying to keep a fixed element visible at the top of the page while also having content with varying heights. Here is the CSS code for the fixed element: div.topfloat { position: fixed; top: 0; width: 100%; } The issue I'm facing is ...