N6DYN
N6DYN

Reputation: 325

ReactJS/GraphQL: Call query from submit button

When my app loads the query below runs and the result from the DB is displayed in the browser. However, my app also has a submit button. How can run this entire component when the submit button is pressed while passing the timestamp input from the submit?

handleSubmit(event) {
  event.preventDefault();
  console.log(this.state.inputValue)
  this.state = {
    inputValue: new Date(document.getElementById("time").value).valueOf()
  };
  console.log(this.state);            
}

This is the UserList component code:

const UserList = props => (
  <Query
    query={gql`
      query action($timestamp: Float!) {
        action(timestamp: $timestamp) {
          action
          timestamp
          object {
            filename
          }
        }
      }
    `}
  >
    {({ loading, error, data }) => {
      if (loading) return <p>Loading...</p>;
      if (error) return <p>Error</p>;

      return (
        <Item.Group divided>
          {data.action.map(action => (
            <div>
              <ul>
                <li>{action.action}</li>
                <li>{action.timestamp}</li>
                <ul>
                  {action.object.map(obj => {
                    return <li>{obj.filename}</li>;
                  })}
                </ul>
              </ul>
            </div>
          ))}
        </Item.Group>
      );
    }}
  </Query>
);

export default UserList;

Upvotes: 0

Views: 675

Answers (2)

xadm
xadm

Reputation: 8428

Parent component contains submit button and there lives state. Submit handler should only set value in state with ... setState() - NOT directly!

If there is no default state/value use conditional rendering ... in parent render display some placeholder when state (timestamp) is undefined. If value exists pass it as prop:

{!this.state.inputValue ? <SomePlaceholder />
: <UserList timestamp={this.state.inputValue} />}
// place input, submit button where you want (after/before results)

UserList will be called with props - 'props.timestamp' can be used in graphql query literal.

When input changes again submit handler will change parent state and that change will be passed again as prop to child, query fired, results rerendered.

Upvotes: 1

lrcrb
lrcrb

Reputation: 910

Base on the information provided, there's probably several ways to accomplish what you need. I would say the UserList component needs to conditionally render the Query component in some manner. Perhaps UserList takes a boolean prop isSubmitted and while isSubmitted is false, UserList renders a div with text explaining to submit the query. This could be done as the UserList and the submit button being hosted by the same parent component that has state containing a isSubmitted property that changes on click.

Upvotes: 0

Related Questions