Majestic
Majestic

Reputation: 938

Bind this but still get setState is not a function

I have two components in two files: Firebase and Recipe. I call in Recipe a function createRecipe from Firebase file. When I call this.setState({ recipies }) an error occurs. I searched a solution and tried to bind context according to results here.

Firebase file:

class Firebase {
  constructor () {
    app.initializeApp(config)
    
    // TRIED
    this.createRecipe = this.createRecipe.bind(this)
    
    this.auth = app.auth()
    this.db = app.database()
  }

  state = {
    recipies: {}
  }

  createRecipe = recipe => {
    const recipies = {...this.state.recipies}
    recipies[`recipe-${Date.now()}`] = recipe
    this.setState({ recipies })
  }
}

export default Firebase

Recipe file:

import { withAuthorization } from '../Session'
import { withFirebase } from '../Firebase'

class Recipe extends Component {

  state = {
    name: '',
    image: '',
    ingredients: '',
    instructions: ''
  }

  handleChange = event => {
    const { name, value } = event.target
    this.setState({ [name]: value })
  }

  handleSubmit = event => {
    event.preventDefault()
    const recipe = { ...this.state }
    // TRIED
    this.props.firebase.createRecipe(recipe)
    this.props.firebase.createRecipe(recipe).bind(this)
    
    this.resetForm(recipe)
  }

  render () {
    return (
      <div>
        <div className='card'>
          <form
            // TRIED
            onSubmit={this.handleSubmit>
            onSubmit={() => this.handleSubmit>
            onSubmit={this.handleSubmit.bind(this)}>
            
            <input value={this.state.name} type='text' name='nom' onChange={this.handleChange} />
            <input value={this.state.image} type='text' name='image' onChange={this.handleChange} />
            <textarea value={this.state.ingredients} rows='3' name='ingredients' onChange={this.handleChange} />
            <textarea value={this.state.instructions} rows='15' name='instructions' onChange={this.handleChange} />
            <button type='submit'>Add recipe</button>
          </form>
        </div>
      </div>
    )
  }
}

const condition = authUser => !!authUser

export default withAuthorization(condition)(withFirebase(Recipe))

Do you have an idea about what's going wrong ? Many thanks.

Upvotes: 1

Views: 119

Answers (2)

Satheesh
Satheesh

Reputation: 11276

class Firebase doesn't extend React.component so it doesn't know what state is. This is expected, extend React.component or use state hooks useState().

Upvotes: 1

You are not using react in your Firebase component

How to fix:

import React, {Component }from 'react';

class Firebase extends Component {
 constructor(props){
    super(props)  
    // your code
}
// your code

render(){
   return null; // this won't change anything on your UI
}

}

Upvotes: 0

Related Questions