Beginner Alert! :) I am setting FormData in child component and then passing it to the parent component using formReducer and dispatch, but in parent formData.entries() is always empty!
ChildComponent.js
function ChildComponent({signed, fileAttached}){
const { dispatch } = useContext(ContactFormContext);
const changeHandler = (event) => {
const formData = new FormData();
formData.append('File', event.target.files[0]);
dispatch({ type: "FILE_ATTACHED", payload: formData })
};
return (
<>
<div>
<input type="file" name="file" onChange={changeHandler} />
</div>
</>);
}
ParentComponent.js
function useFormProgress(fileAttached) {
function goForward() {
const currentStep = 1;
let appvariables = [
{
"key": "PUID",
"value": "a2sd"
},
{
"key": "ApplicationNames",
"value": "Trello, abc"
}
];
switch(currentStep) {
case 0:
break;
case 1:
console.log(fileAttached);
if(fileAttached != null)
sendEmail("Resignation Letter", appvariables, fileAttached);
break;
}
}
return [goForward];
}
function sendEmail(templateName, variables, attachment){
console.log("sending email...");
const requestBody = {
"templateName": templateName,
"recipients": [
"abc@xyz.com"
],
"variables": variables,
"files": attachment
};
fetch('https://localhost:5001/api/Email',{
method:'Post',
body: JSON.stringify(requestBody),
headers:{'Content-Type': 'application/json'},
});
}
const initialState = {
signed: "",
fileAttached: null
};
function formReducer(state, action) {
switch (action.type) {
case "SIGNED":
return { ...state, signed: action.payload };
case "FILE_ATTACHED":
return {...state, fileAttached: action.payload};
default:
throw new Error();
}
}
function ParentComponent() {
const [state, dispatch] = useReducer(formReducer, initialState);
const { signed, fileAttached } = state;
const steps = [<ChildComponent {...{signed, fileAttached}}/>];
const [goForward] = useFormProgress(fileAttached);
return (
<ContactFormContext.Provider value={{ dispatch }}>
<div>{steps[0]}
<div><button onClick={e => {
e.preventDefault();
goForward();
}}
> Parent Button
</button>
</div>
</div>
</ContactFormContext.Provider>
);
}
ContactFormContext.js
const ContactFormContext = React.createContext();
In the switch statement above (ParentComponent), the console.log(FileAttached) shows FormData with 0 entries(see image attached), also the API request is not successful.!
you can try it out in https://jscomplete.com/playground
add context on top
add child component code
add parentcomponent code
add the following line
ReactDOM.render(<ParentComponent/>, mountNode);
MyAPI Method
[HttpPost]
public JsonResult Get(EmailRequest email)
{
//the request never comes here
}
EmailRequest.cs
public class EmailRequest
{
public string TemplateName { get; set; }
public string[] Recipients { get; set; }
public List<Variables> Variables { get; set; }
public FormFileCollection files { get; set; }
}