Developer Strange
Developer Strange

Reputation: 2198

TypeError when use the React hooks- useReducer

enter image description hereI tried to use the react hooks(useReducer). i got error

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

Here i am attached my code and attached the error screenshot also.

import React, { useReducer } from 'react';

function appReducer(state, action){
    switch(action.type){
        case 'add':
            return [
                ...state,
                {
                    id:Date.now(),
                    text:'',
                    completed:false
                }
            ]
        break;
        default:
        break;
    }
}

export default function myCom(){
    const [state, dispatch] = useReducer(appReducer, []);
    return (
        <div className="App">
            <h5>React ToDo</h5>
            <button onClick={() => dispatch({type:'add'})}>New Todo</button>
            {
                state.map(item =>(
                    <div key={item.id}>{item.id}</div>
                ))
            }
        </div>
    );
}]

How to fix this error.

Upvotes: 0

Views: 4057

Answers (1)

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85545

The error is not of useReducer but you have wrongly used the export default:

export default function myCom(){

If you want to export named function, then you could do:

// function definition
function myComp() {}
// then export
export default { myComp }

Then you can use like:

import Something from '...'
Something.myComp()

But if there's only one function that you wanted to export then I will do it as:

export const myComp = () => {}

Now, you can import like:

import { myComp } from '...'
myComp()

Upvotes: 2

Related Questions