簡體   English   中英

材料表在突變后不更新表數據

[英]Material Table not updating table data after mutation

當用戶添加附加信息時,對添加新信息的數據庫進行更改,然后更新本地狀態,將新信息添加到潛在客戶中。

我的突變和狀態似乎更新得很好,問題似乎是材料表組件的狀態與其“數據”屬性不匹配。 我可以在 React Dev 工具中看到狀態在父組件中更新並且正在傳遞,在我手動刷新頁面之前,該表似乎只是在使用陳舊數據。

我將附上 React Devtools 的圖像以及一些代碼片段。 任何幫助將非常感激。

Devtools 材料表數據道具: Devtools 材料表狀態

材料表父組件:

const Leads = () => {

    const [leadState, setLeadState] = useState({});
    const [userLeadsLoaded, setUserLeadsLoaded] = React.useState(false);
    const [userLeads, setUserLeads] = React.useState([]);
    const { isAuthenticated, user, loading } = useAuth()

    const [
        createLead,
        { data,
            // loading: mutationLoading,
            error: mutationError },
    ] = useMutation(GQL_MUTATION_CREATE_LEAD);

    const params = { id: isAuthenticated ? user.id : null };

    const {
        loading: apolloLoading,
        error: apolloError,
        data: apolloData,
    } = useQuery(GQL_QUERY_ALL_LEADS, {
        variables: params,
    });

    useEffect(() => {
        if (apolloData) {
            if (!userLeadsLoaded) {
                const { leads } = apolloData;
                const editable = leads.map(o => ({ ...o }));
                setUserLeads(editable);
                setUserLeadsLoaded(true);
            };
        }
    }, [apolloData])


    if (apolloLoading) {
        return (
            <>
                <CircularProgress variant="indeterminate" />
            </>
        );
    };

    if (apolloError) {
        console.log(apolloError)
        //TODO: Do something with the error, ie default user?
        return (
            <div>
                <div>Oh no, there was a problem. Try refreshing the app.</div>
                <pre>{apolloError.message}</pre>
            </div>
        );
    };
    return (
        <>
            <Layout leadState={leadState} setLeads={setUserLeads} leads={userLeads} setLeadState={setLeadState} createLead={createLead}>
                {apolloLoading ? (<CircularProgress variant="indeterminate" />) : (<LeadsTable leads={userLeads} setLeads={setUserLeads} />)}
            </Layout>
        </>
    )
}

export default Leads

處理添加附加信息的提交功能:

const handleSubmit = async (event) => {
        event.preventDefault();

        const updatedLead = {
            id: leadState.id,
            first_name: leadState.firstName,
            last_name: leadState.lastName,
            email_one: leadState.email,
            address_one: leadState.addressOne,
            address_two: leadState.addressTwo,
            city: leadState.city,
            state_abbr: leadState.state,
            zip: leadState.zipCode,
            phone_cell: leadState.phone,
            suffix: suffix,
            address_verified: true
        }
        const { data } = await updateLead({
            variables: updatedLead,
            refetchQueries: [{ query: GQL_QUERY_GET_USERS_LEADS, variables: { id: user.id } }]
        })
        const newLeads = updateIndexById(leads, data.updateLead)
        console.log('New leads before setLeads: ', newLeads)
        setLeads(newLeads)
        // setSelectedRow(data.updateLead)
        handleClose()
    };

材料表組件:

const columnDetails = [
  { title: 'First Name', field: 'first_name' },
  { title: 'Last Name', field: 'last_name' },
  { title: 'Phone Cell', field: 'phone_cell' },
  { title: 'Email', field: 'email_one' },
  { title: 'Stage', field: 'stage', lookup: { New: 'New', Working: 'Working', Converted: 'Converted' } },
  { title: 'Active', field: 'active', lookup: { Active: 'Active' } },

];

const LeadsTable = ({ leads, setLeads }) => {
  const classes = useStyles();
  const { user } = useAuth();
  const [isLeadDrawerOpen, setIsLeadDrawerOpen] = React.useState(false);
  const [selectedRow, setSelectedRow] = React.useState({});

  const columns = React.useMemo(() => columnDetails);

  const handleClose = () => {
    setIsLeadDrawerOpen(!isLeadDrawerOpen);
  }
  console.log('All leads from leads table render: ', leads)
  return (
    <>
      <MaterialTable
        title='Leads'
        columns={columns}
        data={leads}
        icons={tableIcons}
        options={{
          exportButton: false,
          hover: true,
          pageSize: 10,
          pageSizeOptions: [10, 20, 30, 50, 100],
        }}
        onRowClick={(event, row) => {
          console.log('Selected Row:', row)
          setSelectedRow(row);
          setIsLeadDrawerOpen(true);
        }}
        style={{
          padding: 20,
        }}
      />
      <Drawer
        variant="temporary"
        open={isLeadDrawerOpen}
        anchor="right"
        onClose={handleClose}
        className={classes.drawer}
      >
        <LeadDrawer onCancel={handleClose} lead={selectedRow} setLeads={setLeads} setSelectedRow={setSelectedRow} leads={leads} />

      </Drawer>
    </>
  );
};

export default LeadsTable;

嘗試創建一個包含 refetchQueries 和 awaitRefetchQueries: true 的對象。 將該對象作為第二個參數傳遞給 useMutation 鈎子。 請參閱下面的示例:

const [
        createLead,
        { data,
            loading: mutationLoading,
            error: mutationError },
    ] = useMutation(GQL_MUTATION_CREATE_LEAD, {
  refetchQueries:  [{ query: GQL_QUERY_GET_USERS_LEADS, variables: { id: user.id } }],
  awaitRefetchQueries: true,
});

手動更新緩存。 示例打擊是添加一個新的待辦事項。 在您的情況下,您可以在編寫查詢之前找到並更新記錄。

const updateCache = (cache, {data}) => {
    
    // Fetch the todos from the cache
    const existingTodos = cache.readQuery({
      query: GET_MY_TODOS
    });
    // Add the new todo to the cache (or find and update an existing record here)
    const newTodo = data.insert_todos.returning[0];
    cache.writeQuery({
      query: GET_MY_TODOS,
      data: {todos: [newTodo, ...existingTodos.todos]}
    });
  };
  const [addTodo] = useMutation(ADD_TODO, {update: updateCache});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM