1

Using Reactjs and Typescript, I have a parent component with data from api. It clicks to open a MUI Dialog with a form to edit but needs to be prepopulated with the data from the parents component. The parent gets its data from an api.Its is not getting the data in the textfield of the dialog and giving error for 'PostData.email' in the child component. **'PostData' is possibly 'undefined'.ts(18048)

(parameter) PostData: {
    id: number;
    name: string;
    email: string;
} | undefined**

Dialog (child )

interface DialogProps {
  isOpen: boolean;
  onClose?: () => void;
  PostData? : {    
    id: number;
    name: string;
    email: string; 
  };
}
const DialogBox: React.FC<DialogProps> = ({ PostData , isOpen, onClose}) => {
    const [open, setOpen] = React.useState(false);   
 
    const handleClickOpen = () => {
        setOpen(true);
      };
    
      const handleClose = () => {
        setOpen(false);
      };


    return (
        <React.Fragment>        
        <Dialog
         open={isOpen}
          onClose={handleClose}
          PaperProps={{
            component: 'form',
            onSubmit: (event: React.FormEvent<HTMLFormElement>) => {
              event.preventDefault();
              const formData = new FormData(event.currentTarget);
              const formJson = Object.fromEntries((formData as any).entries());
              const email = formJson.email;
              console.log(email);
              handleClose();
            },
          }}
        >
          <DialogTitle>Dialog </DialogTitle>
          <DialogContent>
            <DialogContentText>
             Edit Email address
            </DialogContentText>
            {/* {PostData && PostData.email && */}
            <TextField
              autoFocus
              required
              margin="dense"
              id="name"
              name="email"
              label="Email Address"
              type="email"
              fullWidth
              variant="standard" 
              value = {PostData.email}
            />
           {/* } */}
          </DialogContent>
          <DialogActions>
          <Button type="submit">Edit</Button>
            <Button onClick={handleClose}>Cancel</Button>
            
          </DialogActions>
        </Dialog>        
        </React.Fragment>
      );
}
export default DialogBox;

Parent

interface Post {    
    id: number;
    name: string;
    email: string; 
  }
  
  export default function Parent()  {
    const [open, setOpen] = React.useState(false);
    const [posts, setPosts] = useState<Post | null>(null);
    const [error, setError] = useState<string | null>(null);

    const handleClickOpen = () => {
        setOpen(true);
      };
    
      const handleClose = () => {
        setOpen(false);
      };
   

    useEffect(() => {
      const fetchData = async () => {
        try {
          const response = await fetch('https://jsonplaceholder.typicode.com/users/1'); 
          if (!response.ok) {
            throw new Error('Failed to fetch post');
          }
          const data: Post = await response.json();
          setPosts(data);
        } catch (error) {
            if (typeof error === 'string') {
              setError(error);
            } else {
              setError('An error occurred while fetching data');
            }
          }
      };
  
      fetchData();
    }, []);
  
  
    return (
      <React.Fragment>
      <div>
        <h1>Profile</h1>
        {error && <div>Error: {error}</div>} 
        {posts && (
        <div>                 
          <p>Name: {posts.name}</p>
          <Divider/>
          <p>Email: {posts.email}</p>
        </div>
      )}
     
      <Button   onClick={handleClickOpen}>Edit</Button> 
      <DialogBox  isOpen={open} /> 
      </div>
      </React.Fragment>
    );

  };
1
  • value = {PostData && PostData.email || ""} or more cleanly value = {PostData?.email ?? "} Commented May 21, 2024 at 1:13

1 Answer 1

0

You are setting the value of posts in your parent but you are not sending your posts data from parent to the child component in its props i.e., DialogBox.

Change this:

<DialogBox  isOpen={open} />

to:

<DialogBox  isOpen={open} PostData={posts}/>
Sign up to request clarification or add additional context in comments.

1 Comment

I tried and it gives this error Type 'Post | null' is not assignable to type '{ id: number; name: string; email: string; } | undefined'. Type 'null' is not assignable to type '{ id: number; name: string; email: string; } | undefined'.ts(2322) dialogBox.tsx(13, 3): The expected type comes from property 'PostData' which is declared here on type 'IntrinsicAttributes & DialogProps' @natashap

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.