Ad

Using Component State In Another Component React Js

- 1 answer

Im working on a little web app, and im stuck on getting the answers data from answer class that i created.

to sum the project, i have a class createQuiz, where i handle the input for question data, and i have an answerOptions state array to collect all the answers, but i created another component answer to have the states of the answers and when i modify them, the answeroptions dont update. Here is the code for the answer class :

import React, {Component} from 'react';
import createQuiz from './CreateQuiz'



export default class Answer extends Component {
    constructor(props) {
        super(props);

        this.handleInputChange = this.handleInputChange.bind(this);
        this.onChangeAnswerValidity = this.onChangeAnswerValidity.bind(this);
        this.ChangeValidityState = this.ChangeValidityState.bind(this);

        this.state = {       
            answerText : '',
            answerValidity : false
        }
    }

    getCurrentState(){
        return (this.state)
    }


    handleInputChange(event) {

        this.setState({
            answerText : event.target.value
        })
      }

    onChangeAnswerValidity(event){
    this.setState({
        answerValidity : !event.target.value
    })
    }

    ChangeValidityState(event){
        this.setState({
            answerValidity : !event.target.value
        })
    }

    render() {
        return (
            <div>
                <input  type="text"
                        className="form-control"
                        value={this.state.answerText}
                        onChange={this.handleInputChange}
                        />
                        <input  type="radio"
                        className="form-control"
                        value={this.state.answerValidity}
                        checked={this.state.answerValidity}
                        onChange={this.onChangeAnswerValidity}
                        />
            </div>
        )
    }

}

and here is the code for the create quiz class :

import React, {Component} from 'react';
import axios from 'axios';
import Answer from './Answer';


export default class CreateQuiz extends Component {

    constructor(props) {
        super(props);

        this.onChangeQuestion = this.onChangeQuestion.bind(this);
        this.onChangeQuestionTitle = this.onChangeQuestionTitle.bind(this);
        this.onChangeAnswerOptions = this.onChangeAnswerOptions.bind(this);
        this.onAddItem = this.onAddItem.bind(this);
        this.handleInputChange = this.handleInputChange.bind(this);
        this.onChangeQuestionAutor = this.onChangeQuestionAutor.bind(this);
        this.onChangeValue = this.onChangeValue.bind(this);
        this.onChangeAnswerValidity = this.onChangeAnswerValidity.bind(this);
        this.onSubmit = this.onSubmit.bind(this);
    //   this.GenerateAnswers = this.GenerateAnswers.bind(this);


        this.state = {
            questionTitle: '',
            questionAutor: '',
            question: '',
            answers : [],
            answerOptions: [],

        }
    }
    onChangeValue = event => {
    this.setState({ currentAnswerValue: event.target.value });
    };

    onAddItem = () => {
    // not allowed AND not working
    this.setState(state => {
        const newAnswer = {
            answerText : '',
            answerValidity : false
        };
        const list = this.state.answerOptions.push(newAnswer);
        return {
        list,
        };
    });
    };

    handleInputChange(event) {

        const newIds = this.state.answerOptions.slice() //copy the array
        const index = this.state.answerOptions.findIndex((el) => (el.id === event.params.id))
        newIds[index].answerText = event.target.value //execute the manipulations
        this.setState({answerOptions: newIds}) //set the new state
      }
      onChangeAnswerValidity(event){
        const newIds = this.state.answerOptions.slice() //copy the array
        const index = this.state.answerOptions.findIndex((el) => el.answerText === event.target.value)
        newIds[index].answerValidity = event.target.value //execute the manipulations
        this.setState({answerOptions: newIds}) //set the new state
      }

    onChangeQuestionAutor(e){
        this.setState({
            questionAutor: e.target.value
        });
    }

    onChangeQuestionTitle(e) {
        this.setState({
            questionTitle: e.target.value
        });
    }

    onChangeQuestion(e) {
        this.setState({
            question: e.target.value
        });
    }

    onChangeAnswerOptions(e) {
        this.setState({
            answerOptions: e.target.value
        });
    }




    onSubmit(e) {
        e.preventDefault();

        console.log(`Form submitted:`);
        console.log(`questionTitle: ${this.state.questionTitle}`);
        console.log(`questionAutor: ${this.state.questionAutor}`);
        console.log(`question: ${this.state.question}`);
     //   this.GenerateAnswers();
        console.log(`answerOptions: ${this.state.answers}`);

        const newQuiz = {
            questionTitle: this.state.questionTitle,
            questionAutor: this.state.questionAutor,
            question: this.state.question,
            answerOptions: this.state.answers,
        }

        axios.post('http://localhost:4000/quizzes/add', newQuiz)
            .then(res => console.log(res.data));


        this.setState({
            questionTitle: '',
            questionAutor: '',
            question: '',
            answers : [],
            answerOptions: []

        })        

    }

    answerList(){
        return this.state.answerOptions.map(function(currentAnswer, index) {           
            return <Answer answer = {currentAnswer} key = {index}/>;
        });

    }

    // GenerateAnswers(){
    //     const newAnswers = this.state.answers
    //     this.state.answerOptions.map(function(currentAnswer, index){
    //         const newAnswer = this.state.answerOptions[index].getCurrentState()
    //         newAnswers.push(newAnswer)
    //     });
    //     this.setState({answers: newAnswers});
    // }

    render() {
        return (
            <div style={{marginTop: 20}}>
                <h3>Create new question</h3>
                <form onSubmit={this.onSubmit}>
                    <div className="form-group">
                        <label>Question Title: </label>
                        <input  type="text"
                                className="form-control"
                                value={this.state.questionTitle}
                                onChange={this.onChangeQuestionTitle}
                                />
                    </div>
                    <div className="form-group">
                        <label>Question Autor: </label>
                        <input  type="text"
                                className="form-control"
                                value={this.state.questionAutor}
                                onChange={this.onChangeQuestionAutor}
                                />
                    </div>
                    <div className="form-group">
                        <label>Question: </label>
                        <input  type="text"
                                className="form-control"
                                value={this.state.question}
                                onChange={this.onChangeQuestion}
                                />
                    </div>
                    <div>
                        <ul>
                        {this.answerList()}
                        </ul>
                    </div>
                    <div  className="form-group">
                        <button type="button" onClick = {this.onAddItem} className="btn btn-primary"> Add answer </button> 
                    </div>

                    <div className="form-group">
                        <input type="submit" value="submit Question" className="btn btn-primary" />
                    </div>
                </form>
            </div>
        )
    }
}

when i send the data to the database i always have in the answer fields empty string and false no update has been done.

thanks a lot, Boubker ELAMRI

Ad

Answer

You’re modifying the list, so react doesn’t know it’s changed. You need to create a new array first, before setting the state

const list = Array.from(this.state.answerOptions)
list.push(newAnswer)
Ad
source: stackoverflow.com
Ad