0

I am getting response from axio get request updating state on mount and trying to pass the response to the other component.

Code from ChangeQuestions.js:

import React from 'react';
import UserService from "../../services/user.service";
import QuestionTable from './QuestionTable.js'

class ChangeQuestions extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      operator_personal: [],
      operator_preferences: [],
      company_questions: [],
    }
  }

  componentDidMount(){
    UserService.getOperatorPersonalQuestions()
      .then(({ data }) => {
        this.setState({ operator_personal:  data });
      })
      .catch((err) => {})

    UserService.getOperatorPreferencesQuestions()
      .then(({ data }) => {
        this.setState({ operator_preferences:  data });
      })
      .catch((err) => {})

    UserService.getCompanyQuestions()
      .then(({ data }) => {
        this.setState({ company_questions: data });
      })
      .catch((err) => {})
  }
   
  render(){
    const { operator_personal, operator_preferences, company_questions } = this.state;
    return (
      <div>
        {console.log(operator_preferences)}
        <QuestionTable questions={operator_personal}/>
        <QuestionTable questions={operator_preferences}/>
        <QuestionTable questions={company_questions}/>  
        {/* <QuestionTable questions={this.state.connections}/>*/}
      </div>
    );
  }
}

And this is code from QuestionTable component:

import React from 'react';
import Table from 'react-bootstrap/Table';

class QuestionTable extends React.Component{
  constructor(props){
    super(props);
    console.log(props.questions);
    this.state = {
       questions: this.props.questions,
       edit: []
    };
    this.addNewTab = this.addNewTab.bind(this);
  }

  componentDidMount(){
    this.setState(prev => ({
        edit: prev.questions.map(() => [...prev.edit, false]),
        questions: [...this.props.questions]
    }))
  }

  handleEdit = index => {
    this.setState(state => {
      const list = state.edit.map((item, j) => {
        if (j === index) {
          return !item;
        } else {
          return item;
        }
      });
      return {
        edit: list
      };
    });
  }

  handleTitleChange = index => {
    this.setState(state => {
      let temp = {
        "id": '',
        "answers": [ ],
        "typeprofile": "",
        "questiontext": ""
      };
      const list = state.questions.map((it, j) => {
        if (index == j) {
          temp.id = it.id;
          temp.answers = it.answerss;
          temp.typeprofile = it.typeprofile;
          temp.questiontext = document.getElementById(`title${index}`).value;
          return temp;
        }
        return it;
      })
      return {
        questions: list,
      };
    });
  }
  
  handleAnswersChange = index => {
    this.setState(state => {
      let temp = {
        "id": '',
        "answers": [ ],
        "typeprofile": "",
        "questiontext": "",
        "connection": 0
      };
      const string = document.getElementById(`answers${index}`).value;
      const list = state.questions.map((it, j) => {
        if (index == j) {
          temp.id = it.id;
          if (string.indexOf(',') > -1) { 
            temp.answers = string.split(',');
          }
          else temp.answers = [string];
          temp.typeprofile = it.typeprofile;
          temp.questiontext = it.questiontext;
          return temp;
        }
        return it;        
      })
      return {
        questions: list,
      };
    });
  }

  addNewTab(event) {
    event.preventDefault();
    let temp = {
      "id": '',
      "answers": [ ],
      "typeprofile": "",
      "questiontext": "",
      "connection": 0
    };

    this.setState({
      questions: [...this.state.questions, temp],
      edit: [...this.state.edit, true]
    })
  }

  handleDelete = (index) => {
    let array = [...this.state.questions]; // make a separate copy of the array
    let editNew = [...this.state.edit]; 
    if (index !== -1) {
      array.splice(index, 1);
      editNew.splice(index,1)
      this.setState({questions: array, edit: editNew});
    }
  }

  render(){
    const questions = this.state.questions;
    const newSelector = (ans) => {
      const {questions} = this.state;
      return(
        <select>
          {questions.map((it,j) => {
            const temp = ans;
            console.log(temp.length);
            for(let i = 0 ; i<temp.length;i++)
              return(
                <option key={j}>
                  {temp[j]}
                </option>
              );
            })}
         </select>
      );
    }
    return (
        <div>
           <Table striped bordered hover>
             <thead className='bgvi'>
               <tr>
                 <th>Pitanja</th>
                 <th>Odgovori</th>
                 <th>Edituj</th>
               </tr>
             </thead>                
             <tbody>
               {questions.length>=1&&(
               questions.map((item, index) => {
                 return(
                   <>
                     <tr className='even'>
                       <td key = {item.id}>
                         {this.state.edit[index]?
                         (
                           <textarea value={item.questiontext} id={`title${index}`} onChange={() => this.handleTitleChange(index)}  type="text"/>
                         ):
                         (                                            
                           <p>{item.questiontext}</p>
                         )}
                       </td>
                       <td key = {item.id}>
                         {(item.answers.length === 1 || item.answers.length === 0 ) && index===0?
                           (
                            this.state.edit[index]?
                            (
                              <textarea value={item.answers} id={`answers${index}`} onChange={() => this.handleAnswersChange(index)} type="text"/>
                            ):
                            (                                            
                              <p>{item.answers}</p>
                            )
                          ):(
                            this.state.edit[index]?
                              (
                                <textarea value={item.answers} id={`answers${index}`} onChange={() => this.handleAnswersChange(index)} type="text"/>
                                                
                              ):
                              (
                                newSelector(item.answers,index)
                              )
                            )}
                          </td>
                          <td key = {item.id}>                     
                            {this.state.edit[index]?
                              (
                                <button onClick={() => this.handleEdit(index)}>Sačuvaj</button>
                              ):
                              (
                                <button onClick={() => this.handleEdit(index)}>Edituj</button>
                              )}
                            <button onClick={() => this.handleDelete(index)}>Izbriši</button>

                          </td>
                          <button id="addNewTab" onClick={this.addNewTab}>Dodaj</button>
                        </tr>
                      </>
                    );
                  }
                )
              )
            }
          </tbody>
        </Table>
      </div>
    );
  }
}


export default QuestionTable;

The problem I experience is that questions from state can not get the passed as prop. I keep getting empty array for questions variable. I've tried everything. Any help would be appreciated!

7
  • Can you see the questions inside your ChangeQuestions class? Commented Jun 25, 2020 at 7:20
  • what do you get for the {console.log(operator_preferences)} in ChangeQuestions component? Commented Jun 25, 2020 at 7:22
  • 2
    QuestionTable should implement the componentDidUpdate lifecycle function to pick up when the questions prop changes, i.e. when the data is populated in ChangeQuestions. Commented Jun 25, 2020 at 7:22
  • Yes, I can see the response = questions in [{}] format before they get passed as props Commented Jun 25, 2020 at 7:22
  • put console.log(props.questions) inside render function of QuestionTable you will probably see the data Commented Jun 25, 2020 at 7:23

1 Answer 1

1

Hi you can add this piece of code in QuestionTable component

componentDidUpdate(prevProps,prevState) {
  // Typical usage (don't forget to compare props):
  if (this.props.questions !== prevProps.questions) {
       let newQuestions = [...this.props.questions];
    this.setState({questions:newQuestions});
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.