TypeError: util__WEBPACK_IMPORTED_MODULE_4___default(...) is not a function

Viewed 7077

I have a server.js file that opens a database with node. I'm trying to import this into an index.js file through a lib directory and I have two files in it:

// App.js
import React from 'react';
import addName from "util";

function App() {
  const [name, setName] = React.useState("")

  function handleUpdate(evt) {
    setName(evt.target.value);
  }

  async function handleAddName(evt) {
    await addName(name);
  }

  return <div>
    <p><input type='text' value={name} onChange={handleUpdate} /></p>
    <button className='button-style' onClick={handleAddName}>Add Name</button>
  </div>
}

export default App;
// util.js
import "isomorphic-fetch"

export function addName(name) {
    return fetch('http://localhost:3001/add-time', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name, time: Date.now() })
    })
}

This gives me:

TypeError: util__WEBPACK_IMPORTED_MODULE_4___default(...) is not a function.

I didn't think it would make much of a difference, but on line three of the App.js file I added two curly brackets to make it import {addName} from "util";.

This then gives me the error: TypeError: Object(...) is not a function. Both of these are pointing to line 13 of App.js, await addName(name);. Now, I'm exporting the addName(name) function from `util.js, so I don't understand what this error is.

When I googled the errors, it seemed to lead me to answers that didn't really work for my situation.

1 Answers

With

import addName from "util";

you're importing the default export from util. But what you exported was a named export here:

export function addName(name) {

Either use a default export instead:

export default function addName(name) {

Or import the named one instead:

import { addName } from 'util';
Related